简体   繁体   English

字符串中最长的Palindrome没有循环Python 3

[英]Longest Palindrome in a String without loops Python 3

I'm trying to make a function that finds the longest palindrome in a string without using for loops. 我正在尝试创建一个函数,在不使用for循环的情况下找到字符串中最长的回文。 If there are palindromes of the same length it with produce the one that comes first alphabetically. 如果有相同长度的回文,则产生首先按字母顺序排列的回文。 examples: "" => "", "bcd" => "b", "acaba" => aba 示例:“”=>“”,“bcd”=>“b”,“acaba”=> aba

I found this on overflow which is similar except it uses for loops and it finds the first palindrome. 我在溢出时发现这个类似,除了它使用for循环并找到第一个回文。

def palindromes(text):
    results = []

for i in range(len(text)):
    for j in range(0, i):
        chunk = text[j:i + 1]

        if chunk == chunk[::-1]:
            results.append(chunk)

return text.index(max(results, key=len)), results

A method I was thinking of using is to check if each substring is equal to it's reverse substring[::-1]. 我想用的方法是检查每个子串是否等于它的反向子串[:: - 1]。 But I don't know how to get each possible substring. 但我不知道如何获得每个可能的子串。 I know with recursion I could remove the last or first position of the string but that wouldn't check the substrings in the middle. 我知道递归我可以删除字符串的最后一个或第一个位置,但不会检查中间的子串。

With recursion you can simplify to either match itself, or check recursively beginning of string without last character or end of string without first character: 使用递归,您可以简化为自身匹配,或者在没有第一个字符的情况下检查没有最后一个字符或字符串结尾的字符串的递归开头:

def palindromes(text):
    if text == text[::-1]:
        return len(text)
    return max(palindromes(text[:-1]), palindromes(text[1:]))

The complexity is quite bad - exponential, though. 然而,复杂性非常糟糕 - 指数级。

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

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