You are given a string 'STR'. Your task is to count the number of homogenous substrings of ‘STR’. A substring is said to be homogenous, if and only if all the characters in the substring are the same. Also, a substring is a contiguous sequence of characters of the given string.
Input Format :
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then the test cases are as follows.
The first and the only line of each test case contains the string 'STR'.
Output Format :
For each test case, print an integer denoting the count of homogenous substrings.
Print the output of each test case in a separate line.
Note :
You don’t need to print anything; It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 100
1 <= |STR| <= 10000
String STR contains only lowercase letters
Where '|STR|' denotes the length of the string.
Time limit: 1 sec
2
bcbc
ccddd
4
9
In the first test case,
The homogenous substrings in the given string are:
“b” appears 2 times, and “c” appears 2 times, so total 4 homogenous substrings. Hence, the answer is 4 in this case.
In the second test case,
“c” appears 2 times, “cc” appears 1 times, “d” appears 3 times, “dd” appears 2 times and “ddd” appears 1 time, so total 9 homogenous substrings. Hence, the answer is 9 in this case.
2
aaaaa
baabaab
15
9
Can you think of checking each substring?
The basic approach is to create all possible substrings from the given string and then count the number of homogenous substrings from them.
Algorithm:
O(N^3), where N is the size of the string.
Since there are O(N^2) substrings that can be created using the string and each substring takes O(N) time to iterate through, the overall Time Complexity is O(N^3).
O(1).
Constant extra space is required. Hence, the overall Space Complexity is O(1).