Valid Palindrome III Problem
Description
LeetCode Problem 1216.
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 <= 1000sconsists of only lowercase English letters.1 <= k <= s.length
Solution
Approach: Longest Palindromic Subsequence
Removing characters from s leaves a subsequence. So the question is whether s has a palindromic subsequence of length at least n - k: the fewest removals needed is n minus the length of the longest palindromic subsequence.
Let f[i][j] be the length of the longest palindromic subsequence of s[i..j]. A single character is a palindrome, so f[i][i] = 1. For i < j:
- If
s[i] == s[j], both ends can wrap the best palindrome inside:f[i][j] = f[i+1][j-1] + 2. - Otherwise at least one of the two ends is not used:
f[i][j] = max(f[i+1][j], f[i][j-1]).
Each entry needs entries of shorter ranges, so fill i from right to left and j from left to right. When j == i + 1 and the two characters are equal, f[i+1][j-1] is f[i+1][i], an empty range, which stays 0 as it should.
The answer is n - f[0][n-1] <= k. Comparing with the full-string value at the end also covers n = 1, where the loop over pairs never runs.
Complexity: O(n2) time and O(n2) extra space.
class Solution:
def isValidPalindrome(self, s: str, k: int) -> bool:
n = len(s)
# f[i][j] = length of the longest palindromic subsequence of s[i..j]
f = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
f[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1] + 2 # f[i+1][i] is 0 when j == i + 1
else:
f[i][j] = max(f[i + 1][j], f[i][j - 1])
# Keeping the longest palindromic subsequence removes the fewest characters.
return n - f[0][n - 1] <= k