214 Shortest Palindrome

214 Shortest Palindrome 

这道题会用到一个算法在 这里用过

利用这个算法稍作改进即可

class Solution:
    def shortestPalindrome(self, s):
        T = '#'.join('${}&'.format(s))
        ans = 0
        p = [0] * len(T)
        C, R = 0, 0
        for i in range(1, len(T)/2 + 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]
            if p[i] == i-1:
                ans = i
        if ans % 2 == 1:
            return s[ans/2:][::-1] + s[ans/2:]
        else:
            return s[ans/2:][::-1] + s[ans/2-1:]
        

 

posted @ 2015-08-06 00:34  dapanshe  阅读(93)  评论(0编辑  收藏  举报