题目:给定一个字符串s,找到它的最长的回文子串。假设s的最大长度为1000。
例:Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Input: "cbbd" Output: "bb"
回文字符串就是指前后是对称的字符串。
需要考虑的特殊情况:
1. Input: "" Output: "" ;
2. Input: "a" Output: "a" ;
3. Input: "ab" Output: "a" 或者 "b";
方法一:最简单的思路就是遍历找到所有子串,判断子串是不是回文子串,再从中找到最长回文子串(将回文子串存储在字典中),但是时间复杂度高,为O(n^2)。
class Solution:
def longestPalindrome(self, s: str) -> str:
len_s=len(s)
if len_s<=1:
return s
maxlen=0
dic={}
for i in range(len_s):
for j in range(i,len_s):
if s[i:j+1]==s[i:j+1][::-1]:
if maxlen<(j-i+1):
dic[j-i+1]= s[i:j+1]
maxlen=max(maxlen,j-i+1)
if dic:
return dic[max(list(dic.keys()))]
else:
return
方法二:先遍历回文串的中心s[i],然后向两边扩展看是否对称,L,R分别表示左右指针。如果lenS - i <= maxLen / 2,说明以i为中心的回文子串长度都不会超过maxLen,直接跳出循环。此外,要考虑如果长度为偶数值的回文子串中心有两个。
class Solution:
def longestPalindrome(self, s: str) -> str:
lenS = len(s)
if lenS <= 1:
return s
minStart, maxLen, i = 0, 1, 0
while i < lenS:
if lenS - i <= maxLen / 2:
break
L, R = i, i
while R < lenS - 1 and s[R] == s[R + 1]:
R += 1
i = i + 1
while R < lenS - 1 and L and s[R + 1] == s[L - 1]:
R, L = R + 1, L - 1
if R- L + 1 > maxLen:
minStart, maxLen = L, R - L + 1
return s[minStart: minStart + maxLen]