leetcode - 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

Solution

Recursive

Similar to 680. 验证回文字符串 Ⅱ, this time we could delete k characters.

Similarly, use recursive + memo.

Time complexity: o ( n k ) o(nk) o(nk)
Space complexity: o ( n k ) o(nk) o(nk)

Longest Palindromic Sequence

We can find the longest palindromic sequence in s, and if len(longest_palindromic_sequence) + k > len(s), that means even after deleting k characters, the string is still not palindromic.

Time complexity: o ( n 2 ) o(n^2) o(n2)
Space complexity: o ( n 2 ) o(n^2) o(n2)

Code

Recursive

class Solution:
    def isValidPalindrome(self, s: str, k: int) -> bool:
        memo = {}
        def helper(left: int, right: int, k: int) -> bool:
            if (left, right, k) in memo:
                return memo[(left, right, k)]
            while left <= right:
                if s[left] == s[right]:
                    left += 1
                    right -= 1
                elif k > 0:
                    res = helper(left + 1, right, k - 1) or helper(left, right - 1, k - 1)
                    break
                else:
                    res = False
                    break
            memo[(left, right, k)] = res if left <= right else True
            return memo[(left, right, k)]
        return helper(0, len(s) - 1, k)

Longest Palindromic Sequence

class Solution:
    def isValidPalindrome(self, s: str, k: int) -> bool:
        def longest_palindromic_sequence(s: str) -> int:
            dp = [[0] * len(s) for _ in range(len(s))]
            # init
            for i in range(len(s)):
                dp[i][i] = 1
            # dp
            for i in range(len(s) - 2, -1, -1):
                for j in range(i + 1, len(s)):
                    if s[i] == s[j]:
                        dp[i][j] = 2 + dp[i + 1][j - 1]
                    else:
                        dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
            return dp[0][len(s) - 1]
        lps = longest_palindromic_sequence(s)
        return len(s) - lps <= k
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值