Given a string str. You are allowed to delete only some contiguous characters if all the characters are same in a single operation. The task is to find the minimum number of operations required to completely delete the string.
Input: str = “abcddcba”
Delete dd, then the string is “abccba”
Delete cc, then the string is “abba”
Delete bb, then the string is “aa”
Delete aa, then the string is null.
Input: str = “abc”
Approach: The problem can be solved using <a href="http://wwl<=iDynamic Programming and Divide and Conquer technique.
Let dp[l][r] be the answer for sub-string s[l, l+1, l+2, …r]. Then we have two cases:
- The first letter of the sub-string is deleted separately from the rest, then dp[l][r] = 1 + dp[l+1][r].
- The first letter of the sub-string is deleted alongside with some other letter (both letters must be equal), then dp[l][r] = dp[l+1][i-1] + dp[i][r], given that l ≤ i ≤ r and s[i] = s[l].
The following two cases can be recursively called along with memoization to avoid repetative function calls.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimum steps to remove substring 010 from a binary string
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Minimum number of steps needed to remove the substring K from given string
- Find largest word in dictionary by deleting some characters of given string
- Minimum characters to be replaced to remove the given substring
- Minimum length substring with exactly K distinct characters
- Minimum time to write characters using insert, delete and copy operation
- Searching characters and substring in a String in Java
- Find the String having each substring with exactly K distinct characters
- Longest substring of only 4's from the first N characters of the infinite string
- Find the longest substring with k unique characters in a given string
- Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
- Minimum changes required to make first string substring of second string
- Find minimum number of steps to reach the end of String
- Minimum steps to convert one binary string to other only using negation
- Minimum deletions from string to reduce it to string with at most 2 unique characters
- Minimum splits in a binary string such that every substring is a power of 4 or 6.
- Minimum flips required in a binary string such that all K-size substring contains 1
- Generate a string of size N whose each substring of size M has exactly K distinct characters
- Longest suffix such that occurrence of each character is less than N after deleting atmost K characters