码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Palindrome III

时间:2020-02-08 10:14:38      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:int   ges   ase   tran   ret   ble   rom   sub   case   

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

这是一道典型的dp题,用dp[][]来存储i,j两个pointer指向的string的一个char, 分别按照相等和不相等来处理即可。

最后,如果length - dp[0][length - 1] <= K, 表明可以,否则不可以。

这题和516. Longest Palindromic Subsequence 本质上是一样的。

 1 class Solution {
 2     public int longestPalindromeSubseq(String s) {
 3         int length = s.length();
 4         int[][] dp = new int[length][length];
 5         for (int i = 0; i < length; i++) {
 6             dp[i][i] = 1;
 7         }
 8         for (int subLength = 2; subLength <= length; subLength++) {
 9             for (int i = 0; i + subLength <= length; i++) {
10                 int j = subLength + i - 1;
11                 if (s.charAt(i) == s.charAt(j)) {
12                     dp[i][j] = dp[i + 1][j - 1] + 2;
13                 } else {
14                     dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
15                 }
16             }
17         }
18         return dp[0][length - 1];
19     }
20 }

 

Valid Palindrome III

标签:int   ges   ase   tran   ret   ble   rom   sub   case   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/12275252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!