LeetCode : No5 Longest Palindromic Substring

题目链接:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值