首页 > 解决方案 > 字符串子串中的最长回文

问题描述

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

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

标签: pythonstringpalindrome

解决方案


我认为您的代码中的问题在于查找子字符串。尝试这个

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

. 此代码将有所帮助


推荐阅读