码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Palindromic Substring

时间:2016-10-07 14:07:23      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

题目如下:

技术分享

此题用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

 

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/CQUTWH/p/5935805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!