Ninja contains a string 'STR'. He has to partition the string 'STR' into a minimum number of partitions such that each partition is a palindrome.
Ninja is stuck and needs your help. Your task is to print the minimum number of cuts required such that each partition of the string 'STR' is a palindrome.
For example:
For the string “abc”, we can create 2 partitions and get 3 palindromic strings "a", "b" and "c".
For the string “abbcb”, we can create 2 partitions and get 3 palindrome strings "a", "b" and "bcb".
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first and only line of each test case contains the string 'STR'.
Output Format:
For each test case, print an integer denoting the minimum number of partitions required such that each partition is a palindrome.
Note
You don’t have to print anything, it has already been taken care of. Just complete the function.
1 <= T <= 10
1 <= | STR | <= 200
STR contains lowercase English alphabets only.
Where ‘T’ is the total number of test cases and | STR | represents the length of the string STR.
Time Limit: 1 sec
2
rohit
abb
4
1
In the first test case, the minimum partitions required are 4 which will make palindrome substrings as: ‘r’, ‘o’, ‘h’, ‘i’ and ‘t’.
In the second test case, the minimum partitions required is 1 which will make palindrome substrings as: ‘a’ and ‘bb’.
2
abba
aakaashh
0
2
In the first test case, the given string itself is a palindrome. Thus, there is no need to make any cuts.
In the second test case, thepartitioned strings are as follows: ‘aakaa’, ‘s’ and ‘hh’.
Can you do this recursively? Try to solve the problem by solving its subproblems first.
This problem can be solved by solving its subproblems and then combining the solutions of the solved subproblems to solve the original problem. We will do this using recursion. The idea is to use recursion to reduce the big problem into several small subproblems.
Here is the algorithm :
O(N * (2 ^ N)), where N is the length of the string ‘STR’.
The length of the string is N and the partition can be made between any two letters. Thus, there are 2 ^ (N - 1) positions. Hence, there will be 2 ^ (N - 1) recursive calls and in each call, we are checking whether the substring is a palindrome or not in O(N) time. Thus, the final time complexity is O(N * 2 ^ (N)).
O(N), where N is the length of the string ‘STR’.
We are not using any external data structure. Only recursion stack space of O(N) size is used by the algorithm.