![]() |
VOOZH | about |
Given a string s, find out if the string is k-Palindrome or not. A k-palindrome string transforms into a palindrome on removing at most k characters from it.
Examples :
Input: s = "abcdecba", k = 1
Output: true
Explanation: String can become palindrome by removing 1 character i.e. either d or e.Input: s = "abcdeca", k = 2
Output: true
Explanation: Can become palindrome by removing 2 characters b and e.Input: s= "acdcb", k = 1
Output: false
Explanation: String can not become palindrome by removing only one character.
Table of Content
If we carefully analyze the problem, it is basically a variation of Edit Distance. We can modify the Edit Distance problem to consider the given string and its reverse as input and the only operation allowed is deletion. To form a palindrome, the same character has to deleted from both s and its reverse. Therefore, for a string to be k-palindrome, total deletions <= 2*k should hold true.
True
We mainly optimize the above recursive solution using a dp table of size (m+1)x(n+1) where dp[i][j] represents total deletions to match prefixes of lengths i and j. At the end, we return return true if dp[m][n] <= 2*k.
2 * kTrue
The idea to find Longest Palindromic Subsequence (LPS) and subtract its length from total string length to find the number of deletions. We compute LPS using LCS between the string and its reverse. If the number of characters not included in the LPS is at most
k, then the string can be converted into a palindrome by removing at mostkcharacters. Thus, we only need to check whethern - LPS <= k.
n - LPS <= k, return true otherwise falseTrue