字符串子串中最长的回文

问题描述 投票:0回答:2

我正试图在字符串中找到最长的回文,这是我的看法。

def palindrome(x):
    rev = x[::-1]
    a = False
    if (rev==x):
        a = True
    return a


def longest_palindrome(s):

    last = len(s) 
    lst = []
    for i in range (last):
        for j in range (i+1,last):
            b = s[i] + s[j]
            a = palindrome(b)
            if (a==True):
                lst.append(b)
            else:
                continue
    return lst

a = input("Enter the string: ")
longest_palindrome(a)

如果我的输入是“aaba”,它会产生输出['aa','aa','aa'],而输出应该是['aa', 'aba']。我迭代的方式有问题吗?

python string palindrome
2个回答
3
投票

我认为代码中的问题是找到子字符串。试试这个

def palindrome(x):
    if len(x) <= 1: ## This condition checks if the length of the string is 1. And if so, it returns False
        return False
    return x == x[::-1]:


def longest_palindrome(s):

    last = len(s)
    lst = []
    for i in range(last):
        for j in range(i, last): ## Iterate from i to last not i+1 to last
            b = s[i:j+1]         ## Slicing the original string to get the substring and checking if it is a pallindrome or not.
            if palindrome(b):
                lst.append(b)
            else:
                continue
    return lst

a = input("Enter the string: ")
print(longest_palindrome(a))

。这段代码会有所帮助


1
投票

这应该工作正常。

def longest_palindrome(s):

    last = len(s)
    lst = []
    for i in range(last):
        for j in range(i+1, last):
            b = s[i:j+1]       #Here's the catch.
            a = palindrome(b)
            if a:
                lst.append(b)
    return lst

您可以使用print语句进行检查。如果你在代码中添加print语句,你会发现你只需要检查最大长度为2的字符串(“aa”,“ab”,“ba”)。

我希望它有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.