給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。
解題思路:
對於一個字符串,迴文子串存在兩種情況,第一種情況是???a???的迴文子串,第二種情況是???aa???的迴文情況,因此在遍歷字符串中的每一個字符的時候,都考慮這兩種情況:
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) <=0:
return ""
res = "" # 用於保存返回的最長迴文子串
for i in range(len(s)):
str1 = self.expand_center(s,i,i); # 計算以一個字符爲中心的情況
str2 = self.expand_center(s,i,i+1); # 計算以兩個字符爲中心的情況
res = max(str1,str2,res,key=len) # 選擇最長的迴文子串
return res
def expand_center(self, s, i, j):
L = i
R = j
while L>=0 and R <len(s) and s[L]==s[R]: # 如果a=a當L-1,R+1的時候,可能會出現bac的情況,所以返回的值是L+1,和R。不能返回是L+1和R-1,因爲返回字符串是s[i,j]是不包括j位置的字符的
L = L - 1
R = R + 1
return s[L+1:R] # 注意返回的字符串是不包括R位置的字符的