#5 最长回文子串

描述:给定一个字符串s,返回其最长的回文子串。

所谓回文子串,就是正着读和反着读一样。如'asdfgfdsa'

 下面是我的实现。时间复杂度O(n2),写得比较差,代码也乱。(基本思路是:先for i in s,以当前i所在位置向外扩散,直到s[i-count]不等于s[i+count]或超出边界)。注意asbsa和asbbsa的区别。

def longestPalindrome(self, s: str) -> str:
        cur_return = []
        cur_max = 0
        
        if len(s) == 0:
            cur_return = s
        else:
            for i in range(0,len(s)):
                count = 0
                while True:
                    count += 1
                    if i-count<0 or i+count>len(s)-1 or s[i-count]!=s[i+count]:
                        if 2*(count-1)+1 > cur_max:
                            cur_max = 2*(count-1)+1
                            cur_return = s[i-count+1:i+count]
                        break
                    else:
                        if 2*count+1 > cur_max:
                            cur_max = 2*count+1
                            cur_return = s[i-count:i+count+1]
            
            for i in range(0,len(s)-1):
                if s[i] == s[i+1]:
                    count = 0
                    while True:
                        count += 1
                        if i-count<0 or i+1+count>len(s)-1 or s[i-count]!=s[i+1+count]:
                            if 2*(count-1)+2 > cur_max:
                                cur_max = 2*(count-1)+2
                                cur_return = s[i-count+1:i+1+count]
                            break
                        else:
                            if 2*count+2 > cur_max:
                                cur_max = 2*count+2
                                cur_return = s[i-count:i+1+count+1]
                else:
                    continue
        return cur_return

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值