Given a string containing characters as integers only. We need to delete all character of this string in a minimum number of steps where in one step we can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated.
Input : s = “2553432” Output : 2 We can delete all character of above string in 2 steps, first deleting the substring s[3, 5] “343” and then remaining string completely s[0, 3] “2552” Input : s = “1234” Output : 4 We can delete all character of above string in 4 steps only because each character need to be deleted separately. No substring of length 2 is a palindrome in above string.
We can solve this problem using Dynamic programming. Let dp[i][j] denotes the number of steps it takes to delete the substring s[i, j]. Each character will be deleted alone or as part of some substring so in the first case we will delete the character itself and call subproblem (i+1, j). In the second case we will iterate over all occurrence of the current character in right side, if K is the index of one such occurrence then the problem will reduce to two subproblems (i+1, K – 1) and (K+1, j). We can reach to this subproblem (i+1, K-1) because we can just delete the same character and call for mid substring. We need to take care of a case when first two characters are same in that case we can directly reduce to the subproblem (i+2, j)
So after above discussion of relation among subproblems, we can write dp relation as follows,
dp[i][j] = min(1 + dp[i+1][j], dp[i+1][K-1] + dp[K+1][j], where s[i] == s[K] 1 + dp[i+2][j] )
Total time complexity of above solution is O(n^3)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count of Palindromic substrings in an Index range
- Ways to sum to N using array elements with repetition allowed
- Minimum insertions to sort an array
- Shortest Uncommon Subsequence
- Count number of ways to jump to reach end
- Missing characters to make a string Pangram
- Minimum number of deletions to make a sorted sequence
- Convert characters of a string to opposite case
- Longest alternating subsequence
- Clustering/Partitioning an array such that sum of square differences is minimum
- Minimum steps to minimize n as per given condition
- Minimum number of deletions to make a string palindrome
- Longest Palindromic Substring | Set 1
- Palindrome Partitioning | DP-17
- Longest Palindromic Subsequence | DP-12
Improved By : nitin mittal