1)逐个遍历,向两边扩散。分单一扩散(奇数),和双字符扩散(偶数)两种情况考虑
时间复杂度较高
class Solution: def longestPalindrome(self, s: str) -> str: length = len(s) maxlength = 0 for i in range(length): l = i r = i while l >= 0 and r < length and s[l] == s[r]: if maxlength < len(s[l:r+1]): maxlength = len(s[l:r+1]) result = s[l:r+1] l -= 1 r += 1 l = i r = i+1 while l >= 0 and r < length and s[l] == s[r]: if maxlength < len(s[l:r+1]): maxlength = len(s[l:r+1]) result = s[l:r+1] l -= 1 r += 1 return result