给定一个字符串 s,找到最长的回文子字符串。无法理解为什么代码没有返回正确的答案


class Solution(object):
def longestPalindrome(self, s):
current = ""
ans = ""
for n in range(len(s)):
for index in range(n,len(s)):
current += s[index]
print(current)
if self.ispalindrome(current):
print(len(ans),len(current))
ans = max(ans,current)
current = ""
return ans
def ispalindrome(self, s):
return s == s[::-1]

我不明白为什么max函数在最后一次迭代中选择了两个字符串中较小的一个。LeetCode的问题:https://leetcode.com/problems/longest-palindromic-substring/

max(ans, current)以字典方式返回最新的字符串,而不是最长的字符串。

您可以使用max(ans, current, key=len)。也就是说,基于给定函数len的两个位置自变量的最大值。

最新更新