最長迴文子串
給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。
輸入:babad 輸出 bab
- 分析:
- 第一思路是暴力,O(n3) 肯定是不行的。
- 這裏要採用同樣是動態規劃的中心拓展思想:若當前子串[a,b]屬於迴文串,那麼[a+1,b-1]一定也屬於迴文串。同時根據迴文串的個數又分爲兩種情況:當迴文串個數爲奇數時,迴文串中心即初試狀態爲1個字符,爲偶數,迴文串初始狀態爲兩個字符。
- 那麼按索引依次作爲中心進行拓展,記錄最長迴文串的兩個索引位置,最後返回對應子串即可。
- `
- class Solution:
def longestPalindrome(self, s: str) -> str:
lenstr=len(s)
maxl_st=0
maxl_ed=0
for i in range(lenstr):
st_1=i;ed_1=i;
st_2=i;ed_2=i+1
if i+1>=lenstr or s[st_2]!=s[ed_2]:
ed_2=-1;st_2=0
while st_1-1>=0 and ed_1+1<lenstr:
if s[st_1-1]==s[ed_1+1]:
st_1-=1;ed_1+=1
else:break
while st_2-1>=0 and ed_2+1<lenstr:
if s[st_2-1]==s[ed_2+1]:
st_2-=1;ed_2+=1
else:break
len1=ed_1-st_1+1
len2=ed_2-st_2+1
maxl=maxl_ed-maxl_st+1
if len1>len2 and maxl<len1:
maxl_st=st_1
maxl_ed=ed_1
elif len2>len1 and maxl<len2:
maxl_st=st_2
maxl_ed=ed_2
str1=s[maxl_st:maxl_ed+1]
return str1 - `