最长回文子串
给定一个字符串 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 - `