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

来源:互联网 发布:2017淘宝漏洞赚钱方法 编辑:程序博客网 时间:2024/05/18 00:57

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
原创粉丝点击