You are given a string ‘S’. Your task is to find the length of it’s longest possible chunked palindrome. In other words, you have to split the string ‘S’ into ‘K’ substrings ((Sub)1, (Sub)2, (Sub)3, ..., (Sub)K) such that:
1. The substring ‘(Sub)i’ is a non-empty string, for all 1 <= i <= K.
2. (Sub)1 + (Sub)2 + (Sub)3 + … + (Sub)K = ‘S’, which means the concatenation of all the substrings is equal to ‘S’.
3. (Sub)i = (Sub)(K-i+1), for all 1 <= i <= ‘K’.
You have to find the largest possible value of ‘K’
Note :
1. The string ‘S’ consists of only lowercase English alphabets.
2. A ‘substring’ is a contiguous sequence of characters within a string.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the ‘T’ test cases follow.
The first and only line of each test case contains a string ‘S’ of lowercase English alphabets.
Output Format :
For each test case, print in a new line an integer denoting the length of the longest possible chunked palindrome of string ‘S’.
Output for each test case will be printed 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 <= |S| <= 1000
where 'T' denotes the number of test cases and |S| denotes the size of the string.
Time Limit: 1 sec
1
abcdefgdefabc
5
We can split the string into “(abc)(def)(g)(def)(abc)”.
1
ninjas
1
We can split the string into “(ninjas)”.
Think Recursively.
O(N^2), where ‘N’ is the size of the input string.
In each function call, we are traversing the string once, but whenever there is a match (to compare the string ‘O(length of the string)’ time required), we call the function again with the remaining substring. Hence the overall time complexity will be O(N^2).
O(N^2), where ‘N’ is the size of the input string.
As we are using an additional memory in terms of HashMap, which will store the output of the previous function’s call. We have to deal with the substrings in each function call, and overall N^2 substrings are possible. Hence, the space complexity will be O(N^2).