[LeetCode] Valid Palindrome III

1216. Valid Palindrome III

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 class Solution {
int dp[1001][1001];
int lps(string& s, int l, int r) {
if(l == r) return 1;
if(l + 1 == r) return s[l] == s[r] ? 2 : -987654321;

if(dp[l][r] != -1) return dp[l][r];
dp[l][r] = INT_MAX;
if(s[l] == s[r])
dp[l][r] = lps(s,l+1,r-1) + 2;
else
dp[l][r] = max(lps(s,l+1,r), lps(s,l,r-1));
return dp[l][r];
}
public:
bool isValidPalindrome(string s, int k) {
memset(dp,-1,sizeof(dp));
return s.length() - k <= lps(s,0,s.length() - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/30/PS/LeetCode/valid-palindrome-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.