繁体   English   中英

通过不仅删除第一个和最后一个字符来确定一个字符串是否是 k 回文

[英]determining if a string is a k-palindrome by not only removing first and last characters

我只是在编写一个程序来确定给定字符串是否是回文,其中最多删除 n 个字母。 我在 python 中提出了一个程序,它只能通过递归删除字符串的第一个或最后一个字符来工作。 它不会删除/检查当您删除不在一端的字符时会发生什么。 我想知道如何改进我的程序,以便它检查所有可能性。 到目前为止,这是我的代码:

def palindromecheck(s,n):
    #print(s)
    #print(n)

    if (len(s)) <=1:
        return True
    if n==0:
        return False
    
    while s[0] == s[(len(s)-1)]:
        s=s[1:-1]
        if len(s) <= 1:
            return True


    
    return palindromecheck((s[:-1]),(n-1)) or palindromecheck((s[1:]),(n-1))

这是一个典型的DP问题。 您可以尝试使用 DP(memo() 辅助函数来保存重复)。 这个想法是找到给定字符串的最长回文子序列。 然后|lps - 原始字符串| <= k,得出该字符串是 k-回文的结论。

def checkPalindrome(s: str, k: int) -> bool:
    # memo to save the repeatition
    memo = {}
 
    def helper(start, end):
        if start >= end: return 0           # <= 1 char is a palindrome
          
        if (start, end) in memo:
            return memo[(start, end)]

        if s[start] == s[end]:
            result = helper(start + 1, end - 1)
        else:
            result = 1 + min(helper(start + 1, end), \
                             helper(start, end - 1))

        memo[(start, end)] = result
        return result

    return helper(0, len(s) - 1) <= k

或者,您可以将 lru_chache 用于中间结果:

from functools import lru_cache
from typing import List


def checkPalindrome(w: str, k: int) -> bool:
    @lru_cache(maxsize=None)
    
    def helper(s, e):            
        if s > e: return 0
        
        if w[s] != w[e]:
            return 1 + min(helper(s+1, e), \
                           helper(s, e-1))
        else:
            return helper(s+1, e-1)
        
    return helper(0, len(w)-1) <= k


w = "asparagus"
k = 4

print(checkPalindrome(w, k))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM