字符串子串中最长的回文

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


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']. 我迭代的方式有问题吗?


智慧大石
浏览 225回答 2
2回答

浮云间

我认为您的代码中的问题在于查找子字符串。尝试这个def palindrome(x):&nbsp; &nbsp; if len(x) <= 1: ## This condition checks if the length of the string is 1. And if so, it returns False&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; return x == x[::-1]:def longest_palindrome(s):&nbsp; &nbsp; last = len(s)&nbsp; &nbsp; lst = []&nbsp; &nbsp; for i in range(last):&nbsp; &nbsp; &nbsp; &nbsp; for j in range(i, last): ## Iterate from i to last not i+1 to last&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b = s[i:j+1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;## Slicing the original string to get the substring and checking if it is a pallindrome or not.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if palindrome(b):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lst.append(b)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; return lsta = input("Enter the string: ")print(longest_palindrome(a)). 此代码将有所帮助

一只甜甜圈

这应该可以正常工作。def longest_palindrome(s):&nbsp; &nbsp; last = len(s)&nbsp; &nbsp; lst = []&nbsp; &nbsp; for i in range(last):&nbsp; &nbsp; &nbsp; &nbsp; for j in range(i+1, last):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b = s[i:j+1]&nbsp; &nbsp; &nbsp; &nbsp;#Here's the catch.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a = palindrome(b)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if a:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lst.append(b)&nbsp; &nbsp; return lst您可以使用打印语句进行检查。如果在代码中添加 print 语句,您会看到最多只检查长度为 2 的字符串(“aa”、“ab”、“ba”)。我希望它有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python