我正确打印输入字符串的每个回文子字符串。然后我返回最后的回文子串,即[“?”]。有一个完美的感觉。
def longestPalindrome(s):
longest = []
palindrome = []
for i in range(len(s)):
for j in range(i, len(s)):
palindrome.append(s[j])
if palindrome == palindrome[::-1]:
print(palindrome)
longest = palindrome
palindrome = []
return longest
print(longestPalindrome("What kind of racecar do you drive?"))
我尝试通过更改if语句来获得最长的回文。
if palindrome == palindrome[::-1] and len(palindrome) > len(longest):
这不按预期工作。我只打印第一个回文[“W”]然后将整个字符串返回列表[“W”,“h”,...]
答案 0 :(得分:0)
当您执行longest = palindrome
时,您将longest
列表的引用指向palindrome
,因此palindrome.append(s[j])
也追加到longest
您需要复制列表。
longest = palindrome[:]
例如,
def longestPalindrome(s):
longest = []
palindrome = []
for i in range(len(s)):
for j in range(i, len(s)):
palindrome.append(s[j])
if palindrome == palindrome[::-1] and len(palindrome) > len(longest):
# print(palindrome, i, j)
longest = palindrome[:]
palindrome = []
return ''.join(longest)
print(repr(longestPalindrome("What kind of racecar do you drive?")))
您的函数应该返回' racecar '
然后使用“修复”。
或者你可以简单地使用字符串而不是列表。