leetcode -- Longest Palindromic Substring -- 重点,有O(n)思路未理解
2015-12-12 21:30
453 查看
https://leetcode.com/problems/longest-palindromic-substring/
这是n^2的解法。
参考/article/4981613.html, 但是他的code是TLE的,因为self.getlongestpalindrome(s, i, i)调用了两次。
更正后:
参考http://fisherlei.blogspot.hk/2012/12/leetcode-longest-palindromic-substring.html
http://www.felix021.com/blog/read.php?2040
这里摘录这句话,做个笔记。 之类mx - i 可以等价于 j - mx的对称点
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
思路1
遍历所有s[i], 当回文串长度为奇数的时候,判断以其为中点的回文串的长度;当回文串长度为偶数的时候,判断以i 和i+1为中点的回文串的长度。这是n^2的解法。
参考/article/4981613.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]为中心的回文子串中,由于 i 和 j 对称,以S[i]为中心的回文子串必然包含在以S[id]为中心的回文子串中,所以必有 P[i] = P[j],见下图。
这里摘录这句话,做个笔记。 之类mx - i 可以等价于 j - mx的对称点
http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
相关文章推荐
- java开发俄罗斯方块学习笔记 Day-2 设计
- iOS项目之Swift新闻App(五)—头条新闻的实现
- Apache Stratos探究:Artifact Distribution Coordinator
- java中的集合之List(二)
- 关于C++队列操作(并附上一道Boring题目)
- My Sql connector Net 安装及C# 连接My Sql数据库
- 用户、组及权限管理
- Prewitt边缘算子
- hdu5593ZYB's Tree 树形dp
- bzoj1408 robot 数论
- Oracle导出DMP文件的两种方法
- PS教程——复古人物海报效果
- 灰色预测模型GM(1,1)
- c++的发展方向
- Ext gridpanel 在chrome错位
- 检查是否有网络工具类
- hdu2795 Billboard(线段树)
- JS模块化工具requirejs简易教程
- cygwin的163镜像(转)
- hdu5596GTW likes gt stl set