LeetCode : No5 Longest Palindromic Substring

来源:互联网 发布:java ssh2默认端口 编辑:程序博客网 时间:2024/06/05 17:31

题目链接:

https://leetcode.com/problems/longest-palindromic-substring/


Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


解法一:

利用Array[i][j] 表示s[i]到s[j]为回文字串,利用动态规划的方式来求解以寻找到最长的回文子串。

class Solution:    # @return a string    def longestPalindrome(self, s):        Array = []        Temp = [0]*len(s)        Temp[0] = 1        Array.append(Temp)        for i in range(1,len(s)):            Temp = [0]*len(s)            Temp[i-1] = 1            Temp[i] = 1            Array.append(Temp)        Max = 0        start = 0        for j in range(1,len(s)):            for i in range(0,j):                if s[i] == s[j]:                    Array[i][j] = Array[i+1][j-1]                    if Array[i][j] and Max < j-i+1:                        Max = j-i+1                        start = i                else:                    Array[i][j] = 0        return s[start:start+Max]<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">        </span>
结果:

Time Limit Exceeded

原因:使用列表,耗时。


解法二:

学习了一种新的算法来处理字符串回文:Manacher's Algorithm

http://blog.csdn.net/pi9nc/article/details/9251455

http://www.felix021.com/blog/read.php?2040

时间复杂度为O(n)

耗时:151ms

class Solution:    # @return a string    def longestPalindrome(self, s):        S = '#' + '#'.join(s) + '#'        i = 0        ID = 0        Mx = 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        Lmax = max(P)        IDmax = P.index(Lmax)        start = IDmax - P[IDmax] + 1        end = IDmax + P[IDmax] - 1        return S[start+1:end:2]

0 0