Given a string
s
and an integer k
, find out if the given string is a K-Palindrome or not.
A string is K-Palindrome if it can be transformed into a palindrome by removing at most
k
characters from it.
Example 1:
Input: s = "abcdeca", k = 2 Output: true Explanation: Remove 'b' and 'e' characters.
Constraints:
1 <= s.length <= 1000
s
has only lowercase English letters.1 <= k <= s.length
Notes:
The key to this question is how to convert the question to an equivalent one.
If we have another string, t, which is just the string s in the reverse order, then this question becomes relevant to the longest common sequence.
If the length of lcs is no smaller than (len - k), it is true.
See the code below:
class Solution { public: bool isValidPalindrome(string s, int k) { string t = s; reverse(t.begin(), t.end()); int len = s.size(); vector<vector<int>> dp(len+1, vector<int>(len+1, 0)); for(int i=1; i<=len; ++i) { for(int j=1; j<=len; ++j) { if(s[i-1] == t[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return len - dp[len][len] <= k; } };
I have learned LCS dp, but don't know apply this to solve this problem until read your solution.
ReplyDeletethanks you creative solution!!!
You are welcome!
Delete