1178. Valid Palindrome III

  • Difficulty: Hard

  • Topics: String, Dynamic Programming

  • Similar Questions:

Problem:

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

Solutions:

class Solution {
public:
    bool isValidPalindrome(string s, int k) {
        int n = s.length();
        vector<vector<int>> dp(n, vector<int>(n, 0));

        for (int len = 2; len <= n; ++len) {
            for (int i = 0; i <= n - len; ++i) {
                int left = i;
                int right = i + len - 1;
                dp[left][right] = 1 + min(dp[left + 1][right], dp[left][right - 1]);
                if (s[left] == s[right]) {
                    dp[left][right] = min(dp[left][right], dp[left+1][right-1]);
                }
            }
        }

        return dp[0][n-1] <= k;
    }
};

results matching ""

    No results matching ""