LeetCode - Longest Palindromic Substring

来源:互联网 发布:创业 知乎 编辑:程序博客网 时间:2024/06/13 02:07

LeetCode - Longest Palindromic Substring

Ths problem is described as following :

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.

方法一:

起初,我采用较为暴力的方法,查找每个可能的回文字串,时间复杂度O(N3),空间复杂度O(1)
具体而言,从每个元素i开始查找,固定开始元素i,从最后一个元素开始找相同字符j,若i~j长度大于当前最长字串的长度,就比较其中间元素,如果是回文的,就更新最长字串,并记录长度。如此往复,当开始元素下标i到最后一个元素的长度都小于当前最长字串的长度,就结束算法。这是一种暴力的方法,但是注意做到了一些优化,然而在测试时,遇到极端情况(1000个a中间插入bc)还是较为消耗时间,所以放弃这一方法,然而代码如下:

class Solution:    # @return a string    def longestPalindrome(self, s):        longest = 0  # to store the length of the longest Palindrome        longstr = ''        i = 0        while i < len(s) and len(s)-i > longest:            j = len(s)-1  # from the last character            while j > i:                if s[j] == s[i] and longest < j-i+1:                    l = i                    r = j                    while l < r and s[l] == s[r]:                        l += 1                        r -= 1                    if not l < r:                        longest = j-i+1                        longstr = s[i:j+1]                        break                j -= 1            i += 1        return longstr

方法二:

之后考虑中心扩展的方法:时间复杂度O(N2),空间复杂度O(1)
这一方法,要注意中心是奇数和偶数两种情况分别讨论。具体编码时,中心值从整个string的中间元素往两侧扩展效率较高,代码如下.

class Solution:    # @return a string    def longestPalindrome(self, s):        if len(s) == 0:            return ''        longest, longstr = 0, ''        i, j = (len(s)-1)/2, len(s)/2        while i >= 0 and j < len(s):            args = [(s,i,i), (s, i, i+1), (s, j, j), (s,j,j+1)]            for arg in args:                stemp = self.PalindromewithCenter(*arg)                if len(stemp) > longest:                    longest, longstr = len(stemp), stemp            if longest >= i*2:                break            i, j = i-1, j+1        return longstr    def PalindromewithCenter(self, s, l, r):        while l >= 0 and r <= len(s)-1 and s[l] == s[r]:            l -= 1            r += 1        return s[l+1:r]
0 0
原创粉丝点击