Ninja loves to play with strings and anagrams. A palindrome is a string that is read the same backward or forward. An anagram is a string that is formed by rearranging the characters of the string. Ninjas have been given a string ‘STR’, and asked to find the number of substrings whose anagram is palindromic.
The first line of the input contains a single integer 'T', representing the number of test cases.
The first line of each test case contains a string ‘STR’.
Output Format :
For each test case, print a single integer representing the number of palindromes.
Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |STR| <= 5*10^3
The string ‘STR’ contains small letters only.
Time Limit : 1 sec
2
aa
abc
3
3
For first test case :
Substring are: {a, a, aa}
Since, all the substrings are palindromes.
So, the result is 3.
For second test :
Substring are: {a, b, c, ab, bc, abc}
Since, all {a, b, c} are palindromes. And no anagram of {ab, bc, abc} have palindromes.
So, the result is 3.
2
aaa
aab
6
5
Try checking for palindromes on all the substrings.
The basic idea is to find all the substrings of the string, and for each substring, find whether any anagram of the substring is palindrome or not. The substring is palindrome or not if the frequency of all the characters except at most one character must be even.
Here is the algorithm :
O(N ^ 3), where ‘N’ is the size of the string.
We traverse the whole string twice to generate all the substrings of the string, and for each substring, we check whether it is palindrome or not by traversing the substring again. Therefore, the overall time complexity will be O(N ^ 3).
O(N), where ‘N’ is the size of the string.
We store the count of all characters of the substring. Therefore, the overall space complexity will be O(N).