题目
5. 最长回文子串
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/28a125e5d5ad2672d2dbe7eb052b6899.png)
解答
代码
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s)==1 or len(s)==0:
return s
if len(s)==2:
if s[0]==s[1]:
return s
else:
return s[0]
ra=s[0]
rb=s[0]
for i in range(1,len(s)-1):
ep=1
while i-ep>=0 and i+ep<len(s) and s[i-ep]==s[i+ep]:
if 2*ep+1>len(ra):
ra=s[i-ep:i+ep+1]
ep+=1
for j in range(0,len(s)-1):
if s[j]==s[j+1]:
if len(rb)<=2:
rb=s[j:j+2]
epd=1
while j-epd>=0 and j+epd+1<len(s) and s[j-epd]==s[j+epd+1]:
if 2*epd+2>len(rb):
rb=s[j-epd:j+epd+2]
epd+=1
if len(ra)>len(rb):
return ra
else:
return rb
思路
- 特殊情况:
- s长度为0、1时:
返回其自身 - s长度为2时:
相同:返回自身
不同:任意返回一个子串(此代码取第一个)
- 一般情况(中心扩展法):
- for寻找奇数回文子串
遍历中心,在检索范围内且两边相等的前提下
用ep不断向外扩展,并且记录满足条件的最长子串ra - for寻找偶数回文子串
同理,只是中心改为两个连在一起的相同字母。epd扩展,rb记录 - 对比ra、rb
返回最长的回文子串
结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cfeb193498053d6423f101e8845ff110.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/900d95247bb5cd76b1cc35e6c8512570.png)