[LeetCode] 最长回文子串[Python]

题目描述:给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。

一开始写了暴力搜索法,结果超时了,就上网找了答案,发现一个博客写的很好,推荐

https://segmentfault.com/a/1190000003914228

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = '#' + '#'.join(s)+'#'

        RL = [0]*len(s)
        MaxRight = 0
        pos = 0
        MaxLen = 0
        for i in range(len(s)):
            if i min(RL[2*pos-i], MaxRight-i)
            else:
                RL[i] = 1
            while i-RL[i]>=0 and i+RL[i]<len(s) and s[i-RL[i]] == s[i+RL[i]]:
                RL[i] += 1
            if RL[i] +i-1 >MaxRight:
                MaxRight = RL[i]+i-1
                pos = i
            MaxLen = max(MaxLen,RL[i])
            if MaxLen == RL[i]:
                MaxList = s[i-RL[i]+1:i+RL[i]]
        return MaxList.replace("#",'')
其实不太明白为什么回文子串只有自己的时候RL[i]=1......

你可能感兴趣的:(LeetCode)