边工作边刷题:70天一遍leetcode: day 40

Longest Palindromic Substring

要点:manchane method太复杂。这里就用dp实现O(n^2)。一种是用boolean dp记录所有左右边界。二重loop所有左右边界。注意为了保证用到dp,一定是距离小的先计算,所以这里的循环方式是外层len(2开始),内层一点。当然这种方法会TLE。
另一种O(n^2)方法:https://discuss.leetcode.com/topic/7144/python-o-n-2-method-with-some-optimization-88ms

  • 从左到右扫一遍,记录最大maxLen。当前作为右边界的情况只有两种可能cases:maxLen+2:这是左右两边扩展1个字符。maxLen+1:右边扩展1个字符,中点shift。

错误点:(第二种方法)

  • 注意两种检测是exclusive的
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        maxLen = 1 # error 2: init =1 not 0
        start = 0 # error 1: should init
        for i in xrange(len(s)):
            if i-maxLen-1>=0 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
                start=i-maxLen-1
                maxLen+=2
                continue # erro 3: should 
            
            if i-maxLen>=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
                start=i-maxLen # error 4: reversed
                maxLen+=1
        # print start,maxLen
        return s[start:start+maxLen]

posted @ 2016-07-06 03:25  absolute100  阅读(166)  评论(0编辑  收藏  举报