LeetCode 1216. Valid Palindrome III Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1216. Valid Palindrome III

Description

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

Solutions

Solution 1: Dynamic Programming

The problem requires us to remove at most k characters to make the remaining string a palindrome. This can be transformed into finding the longest palindromic subsequence.

We define f[i][j] as the length of the longest palindromic subsequence in the substring s[i..j]. Initially, we have f[i][i] = 1 for all i, since each single character is a palindrome.

If s[i] = s[j], then we have f[i][j] = f[i+1][j-1] + 2, since we can add both s[i] and s[j] to the longest palindromic subsequence of s[i+1..j-1].

If s[i] ≠ s[j], then we have f[i][j] = max(f[i+1][j], f[i][j-1]), since we need to remove either s[i] or s[j] to make the remaining substring a palindrome.

Finally, we check whether there exists f[i][j] + k ≥ n, where n is the length of the string s. If so, it means that we can remove at most k characters to make the remaining string a palindrome.

The time complexity is O(n2), and the space complexity is O(n2). Here, n is the length of the string s.

PythonJavaC++GoTypeScriptRust
class Solution: def isValidPalindrome(self, s: str, k: int) -> bool: n = len(s) f = [[0] * n for _ in range(n)] for i in range(n): f[i][i] = 1 for i in range(n - 2, -1, -1): for j in range(i + 1, n): if s[i] == s[j]: f[i][j] = f[i + 1][j - 1] + 2 else: f[i][j] = max(f[i + 1][j], f[i][j - 1]) if f[i][j] + k >= n: return True return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !