Valid Palindrome III

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

思路:这个题目要求去掉最多k个,形成palindorme,那么可以转换为,longest palindrome subsequence 不小于n - k个,也就是 n - LCS <=k

那么这题代码可以完全套用 Longest Palindromic Subsequence的代码,最后只判断最大的palindorme 是否 >= n - k

class Solution {
    public boolean isValidPalindrome(String s, int k) {
        if(s == null || s.length() == 0) {
            return false;
        }
        int n = s.length();
        int[][] dp = new int[n][n];
        for(int i = 0; i < n; i++) {
            dp[i][i] = 1;
        }
        char[] ss = s.toCharArray();
        for(int i = n - 1; i >= 0; i--) {
            for(int j = i + 1; j < n; j++) {
                if(ss[i] == ss[j]) {
                    if(i + 1 < n && j - 1 >= 0) {
                        dp[i][j] = dp[i + 1][j - 1] + 2;
                    }
                } else {
                    // ss[i] != s[j];
                    if(i + 1 < n && j - 1 >= 0) {
                        dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                    }
                }
            }
        }
        return dp[0][n - 1] >= n - k;
    }
}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读