Every year, on the day of Christmas, Everyone at The Dunder Mifflin paper company exchanges gifts. Jim always gives Pam the best Christmas gifts. But this time, Pam decided to give Jim a string having at most two different characters. Pam has a ternary string ‘s’. She wants to know how many total numbers of contiguous strings she can make from ‘s’ to gift Jim.
A ternary string is a string that does not have more than three different characters.
For Example :Let s = “abbc”
Now In this example, Pam can make the following substrings:
a, b, b, c, ab, bb, bc, abb, bbc.
There are a total of 9 strings that she can gift Jim. Hence the answer is 9.
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.
The first line of each test case contains a string ‘s’ denoting the ternary string.
Output Format :
For each test case, print a single integer “answer”, denoting the total number of strings she can make from the given string satisfying the given conditions.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function and return the answer.
1 <= T <= 100
1 <= |S| <= 10^4, where |S| denotes the length of string S.
Time limit: 1 sec
2
abc
aabc
5
8
For the first test case, she can make strings: a, b, c, ab, bc.
Hence the answer is 5.
For the second test case, she can make the following strings - a, a, b, c, aa, ab, bc, and aab.
Hence the final answer is 8.
2
jim
beet
5
9
Iterate through all possible substrings and count all the strings satisfying the given conditions.
In this approach, iterate through all the substrings from 0 to n-1 and count all the strings that satisfy the given conditions.
The steps are as follows:
O( |S| ^ 2 ), where |S| denotes the length of string S
Since we are iterating through the whole string ‘s’ in a nested for loop.
Hence, the total time complexity of this approach will be O( |s| ^ 2 ).
O( 1 ).
We are not using any extra space.
Hence the space complexity will be O( 1 ).