ID | Title | Difficulty | |
---|---|---|---|
Loading... |
1216. Valid Palindrome III
Hard
LeetCode
Problem
Given a string s
and an integer k
, return true
if s
is a k
-palindrome.
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.
Example 2:
Input: s = "abbababa", k = 1
Output: true
Constraints:
1 <= s.length <= 1000
s
consists of only lowercase English letters.1 <= k <= s.length
Code
516. Longest Palindromic Subsequence
class Solution {
public boolean isValidPalindrome(String s, int k) {
int longest = longestPalindromeSubseq(s);
return s.length() - longest <= k;
}
private int longestPalindromeSubseq(String s) {
int[][] dp = new int[s.length()][s.length()];
for (int len = 1; len <= s.length(); len++) {
for (int i = 0; i + len <= s.length(); i++) {
int j = i + len - 1;
if (i == j) {
dp[i][j] = 1;
continue;
}
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][s.length() - 1];
}
}
按 <- 键看上一题!
1212. Team Scores in Football Tournament
按 -> 键看下一题!
1225. Report Contiguous Dates