Input: 'str' = "aaccb"
Output: 2
Explanation: We can make a valid partition like aa | cc | b.
The first line contains the string 'str', the string to be partitioned.
Print the minimum number of cuts to be done so that each partitioned substring is a palindrome.
You do not need to print anything; it has already been taken care of. Just implement the given function.
We can observe that the problem has optimal substructure and overlapping subproblems and hence can be solved using dynamic programming. The idea is to store the results of subproblems so that we do not have to re-compute them when they are needed.
Below is an approach in which smaller subproblems are stored first, which are used to solve the larger sub-problems. The below approach computes two 2-Dimensional arrays 'isPalindrome[][]' and 'cuts[][]' where 'isPalindrome[i][j]' stores if a substring with starting index βiβ and ending index βjβ is a palindrome or not. (isPalindrome[i][i] is true as every string of length 1 is a palindrome)
cuts[i][j] stores the minimum number of cuts needed for a substring with starting index βiβ and ending index βjβ.
We can optimise it for the following cases:
In the previous approach, we calculated the minimum cut while finding all palindromic substring. If we find all palindromic substrings first and then calculate the minimum cut, the solution would optimize.
We can do that in the following way:
Now that we know all the substrings which are Palindromes, We can efficiently find the minimum cuts in the following way: