leetcode -- Longest Palindromic Substring -- 重点,有O(n)思路未理解

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

思路1

遍历所有s[i], 当回文串长度为奇数的时候,判断以其为中点的回文串的长度;当回文串长度为偶数的时候,判断以i 和i+1为中点的回文串的长度。

这是n^2的解法。

参考http://www.cnblogs.com/zuoyuan/p/3777721.html, 但是他的code是TLE的,因为self.getlongestpalindrome(s, i, i)调用了两次。

更正后:

class Solution(object):
    def getlongestpalindrome(self, s, l, r):
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1; r += 1
        return s[l+1 : r]
    def longestPalindrome(self, s):
        palindrome = ''
        for i in range(len(s)):
            str1 = self.getlongestpalindrome(s, i, i)
            len1 = len(str1)
            if len1 > len(palindrome): palindrome = str1
            str2 = self.getlongestpalindrome(s, i, i + 1)
            len2 = len(str2)
            if len2 > len(palindrome): palindrome = str2
        return palindrome

思路2

2D dp。 也是n^2的

参考http://fisherlei.blogspot.hk/2012/12/leetcode-longest-palindromic-substring.html

思路3(最佳)

线性时间的。

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

当 mx - i > P[j] 的时候,以S[j]为中心的回文子串包含在以S[id]为中心的回文子串中,由于 ij 对称,以S[i]为中心的回文子串必然包含在以S[id]为中心的回文子串中,所以必有 P[i] = P[j],见下图。

这里摘录这句话,做个笔记。 之类mx - i 可以等价于 j - mx的对称点

http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值