leetcode-05- Longest Palindromic Substring-python
2016-03-31 16:46
645 查看
求最大回文子串。回文子串即为对称的字符串。
本能笨思路:遍历所有元素当作中心元素,左右移位判断是否相等。注意边界问题,还有就是按照是否有中心元素分为两种情况。
代码如下,理所当然没通过。。vs下自己测试了一些应该算法应该没问题。
同样的思路,cpp代码通过。
还看到manacher算法和后缀数组什么的,原谅我的懒惰。。
本能笨思路:遍历所有元素当作中心元素,左右移位判断是否相等。注意边界问题,还有就是按照是否有中心元素分为两种情况。
代码如下,理所当然没通过。。vs下自己测试了一些应该算法应该没问题。
class Solution(object): def longestPalindrome(self,s): maxlen=0 if len(s)==1: return 1 else: if s[0]==s[1] or s[-1]==s[-2]: maxlen=2 for i in range(1,len(s)-1): j=0 while(i-j >=1 and i+1+j <=len(s)-2 and s[i-j]==s[i+1+j]): j+=1 maxlen=max(maxlen,j*2) j=0 while(i-j-1 >=1 and i+1+j <len(s)-2 and s[i-1-j]==s[i+1+j]): j+=1 maxlen=max(maxlen,j*2+1) return maxlen
同样的思路,cpp代码通过。
class Solution { public: string longestPalindrome(string s) { const int len = s.size(); if(len <= 1)return s; int start, maxLen = 0; for(int i = 1; i < len; i++) { //寻找以i-1,i为中点偶数长度的回文 int low = i-1, high = i; while(low >= 0 && high < len && s[low] == s[high]) { low--; high++; } if(high - low - 1 > maxLen) { maxLen = high - low -1; start = low + 1; } //寻找以i为中心的奇数长度的回文 low = i- 1; high = i + 1; while(low >= 0 && high < len && s[low] == s[high]) { low--; high++; } if(high - low - 1 > maxLen) { maxLen = high - low -1; start = low + 1; } } return s.substr(start, maxLen); } };
还看到manacher算法和后缀数组什么的,原谅我的懒惰。。
相关文章推荐
- Python 操作MySQL数据库
- Python 读取excel
- python安装Theano库
- Python:使用property装饰器将方法转为属性
- python笔记
- Python使用BeautifulSoup库解析HTML基本使用教程
- python urllib2使用心得
- python 打印颜色
- Python使用Mechanize模块编写爬虫的要点解析
- python webdriver 简单框架
- 深刻理解Python中的元类(metaclass)
- Python 中删除列表中所有的空元素
- 【Python】解决Django Admin管理界面样式表(CSS Style)丢失问题
- Python 安装Graphviz 画决策树
- leetcode04-Median of Two Sorted Arrays-python
- python input()与raw_input()
- python匹配文本中全角符号的两种方法
- Python3爬虫韩寒新浪博客文章
- 数据挖掘 关联规则的FP-growth-tree(FP增长树)的python实现 使用方法
- python解析json串与正则匹配对比