首页 > 技术文章 > LeetCode(5)Longest Palindromic Substring

CQUTWH 2016-10-07 13:09 原文

题目如下:

此题用Manacher算法求解,时间复杂度为O(n)

Python代码:

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = "#" + "#".join(s) + "#"
        print s
        i = 0
        mx = 0
        id = 0
        p = [0 ] * len(s)
        while i<len(s):
            if mx > i:
                p[i] = min(p[ 2*id-i],mx-i)
            else:
                p[i] = 1
         
            while i-p[i] >=0 and i+p[i] < len(s) and s[i-p[i]]==s[i+p[i]]:
                p[i] += 1
         
            if mx < p[i]+i:
                mx = p[i] + i
                id = i
            i+=1
        middle = p.index(max(p))
        start = middle-(max(p)-2)
        end = middle+(max(p)-2)+1
        rstr = ''
        for i in range(start,end,2):
            rstr += s[i]
        return rstr

 

推荐阅读