classSolution: deflongestPalindrome(self, s: str) -> str: defhelper(s, i, j): while i >= 0and j < length and s[i] == s[j]: i = i - 1 j += 1 return i+1, j-1 length = len(s) count = 0 result = "" for i inrange(length): left,right = helper(s, i, i+1) if right -left >= count: count = right - left result = s[left:right+1] # 这个地方比较巧妙 left,right = helper(s, i, i) if right -left >= count: count = right - left result = s[left:right+1] return result
classSolution: deflongestPalindrome(self, s: str) -> str: n = len(s) if n < 2: return s dp = [[False]*n for _ inrange(n)] max_length = 1 left = 0 # L 表示子串长度 for L inrange(1, n+1): # i表示左index,j表示右index for i inrange(n): j = L + i - 1 # j非法时,退出循环 if j > n - 1: break if s[i] != s[j]: dp[i][j] = False else: if L <= 2: dp[i][j] = True else: dp[i][j] = dp[i+1][j-1] if dp[i][j] and L > max_length: max_length = L left = i return s[left:left+max_length]