最长回文子串题解

最长回文子串

给定一个字符串 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
  • `
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值