Sushant is learning about palindromes. One day his teacher gave him a string ‘STR’ consisting of only the lowercase letters and asked him to modify the string in such a way that the string doesn’t contain any palindromic substring by replacing the minimum characters present in the given string. Sushant, although a brilliant student, needs your help.
Note:A palindrome is a word, number, phrase, or another sequence of characters that reads the same backward as forward, such as “madam” or “racecar”.
Example:
Given an ‘STR’: ‘aaaaaaa’ The minimum characters that will be replaced are 4. The string can be converted into ‘abcabca’.
Note:
Here are multiple possible answers, for example changing all the elements, but we have to find the minimum replacements possible.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain a string that represents the input string ‘STR’.
Output Format:
For each test case, print an integer denoting the minimum characters that can be replaced such that the string does not contain any palindromic substring of length 1.
Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
1 <= T <= 10^2
1 <= |STR| <= 10^3
Time Limit: 1 sec
2
abcdefg
abcbaxxy
0
2
In the first test case, the number of replaced characters is 0. As there are no substrings present in the given string, hence the answer is 0.
In the second test case, the number of replaced characters is 4. Here, the modified string can become abczaxqy
2
racecar
plattoonp
1
2
In the first test case, the number of replaced characters is 1. Here the string can be modified into racZcar
In the second test case, the number of replaced characters is 2. Here the string can be modified into plataoXnp
Greedily remove the palindromes of length two and three.
The basic idea of this approach is to remove all the palindromes of length two and three. The idea is that if there exists a palindromic substring larger than length 3 then a palindrome of length 2 or 3 is present.
Here is the algorithm:
O(N), where N is the size of the string given ‘STR’.
As we are iterating over the string once and visiting all the string characters, the time complexity is O(N).
O(1),
Because we are not using any extra space for finding our answer.