#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

猜你喜欢

转载自blog.csdn.net/m0_38101326/article/details/87967140