Longest Palindromic Substring

来源:互联网 发布:大数据质量管理 编辑:程序博客网 时间:2024/06/06 07:50

题目:

       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.

解题思路:

1、Brute force solution

     遍历每一个字符串,以找出最长的回文子串。时间复杂度为O(n^3),无法通过测试

class Solution:
    # @param {string} s
    # @return {string}
    def longestPalindrome(self, s):
        def palindromic(s):
            if len(s)<=1:
                return True
            tmp = s[:]
            while(len(tmp)>1):
                if(tmp[0]!=tmp[-1]):
                    return False
                else:
                    tmp = tmp[1:-1]
            return True
            
        res = ''   
        for i in range(len(s)):
            for j in range(len(s)-1,i-1,-1):
                if palindromic(s[i:j+1]) and len(res)<len(s[i:j+1]):
                    res = s[i:j+1]
        return res

2、Dynamic programming solution  (理论上可行,但未实际测试)

       To improve over the brute force solution from a DP approach, first think how we can avoid unnecessary re-computation in validating   palindromes. Consider the case “ababa”. If we already knew that “bab” is a palindrome, it is obvious that “ababa” must be a palindrome since the two left and right end letters are the same.

Stated more formally below:

Define P[ i, j ] ← true iff the substring Si … Sj is a palindrome, otherwise false.

Therefore,

P[ i, j ] ← ( P[ i+1, j-1 ] and Si = Sj )

The base cases are:

P[ i, i ] ← true
P[ i, i+1 ] ← ( Si = Si+1 )

This yields a straight forward DP solution, which we first initialize the one and two letters palindromes, and work our way up finding all three letters palindromes, and so on… 

This gives us a run time complexity of O(N2) and uses O(N2) space to store the table.


3、A simpler approach(最终测试通过)

In fact, we could solve it in O(N2) time without any extra space.

We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2N-1 such centers.

You might be asking why there are 2N-1 but not N centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as “abba”) and its center are between the two ‘b’s.

Since expanding a palindrome around its center could take O(N) time, the overall complexity is O(N2).

class Solution:
    # @param {string} s
    # @return {string}
    def longestPalindrome(self, s):
        def expand(s,l,r):   # expand round ecnter
            while(l>=0 and r<=len(s)-1 and s[l]==s[r]):
                l -= 1
                r += 1
            return s[l+1:r]
        
        res = s[0:1]
        if (len(s)==0):
            return ''
        for i in range(len(s)):
            p1 = expand(s,i,i)
            if(len(p1)>len(res)):
                res = p1
            p2 = expand(s,i,i+1)
            if(len(p2)>len(res)):
                res = p2
        return res
        


0 0