005 Longest Palindromic Substring

005 Longest Palindromic Substring

这道题比较常见的是 O(n*n)的解法 网上有一个十分巧妙的算法 Manacher’s Algorithm

根据这个算法的代码如下

class Solution:
    # @return a string
    def longestPalindrome(self, s):
        T = "%#"+"#".join(s)+"#$"
        lt = len(T)
        p = [0] * lt
        C, R = 0, 0
        for i in range(1, lt-1):
            p[i] = (R > i) and min(R - i, p[2*C - i])
            while T[i + 1 + p[i]] == T[i - 1 - p[i]]:
                p[i] += 1
            if i + p[i] > R:
                C, R = i, i + p[i]
        maxLen, c = max([n,i] for i, n in enumerate(p))
        return s[(c - maxLen)/2 : (c+maxLen)/2]

 

posted @ 2015-08-03 12:43  dapanshe  阅读(111)  评论(0编辑  收藏  举报