LeetCode 5. Longest Palindromic Substring
2016-09-05 19:47
323 查看
题目:
Given a string S,
find the longest palindromic substring in S.
You may assume that the maximum length of S is
1000, and there exists one unique longest palindromic substring.
题意:
求一个子串对最大回文子串,如‘abac‘的回文子串为‘aba’。
思路:
分2种情况,回文为‘aba’和‘aabb’的情况。
依次遍历整个字符串,看当前字符左右两边是否相等。
题解:
Given a string S,
find the longest palindromic substring in S.
You may assume that the maximum length of S is
1000, and there exists one unique longest palindromic substring.
题意:
求一个子串对最大回文子串,如‘abac‘的回文子串为‘aba’。
思路:
分2种情况,回文为‘aba’和‘aabb’的情况。
依次遍历整个字符串,看当前字符左右两边是否相等。
题解:
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ center=[] maxstr='' temp=0 cur='' ccc='' dc=[] length=len(s) if length ==1: return s if length ==2 and s[0]==s[1]: return s if length>2: for i in range(length-1): if s[i-1]==s[i+1] and i-1>=0 and i not in center: center.append(i) if len(center) != 0: index=center[0]+1 #'aba'情况 while index<length and (2*center[0]-index)>=0 and s[index]==s[2*center[0]-index]: cur+=s[index] index+=1 ccc=cur[::-1] maxstr=ccc+s[center[0]]+cur if len(center)>1: i=1 for i in range(len(center)): cur='' index=center[i]+1 while index<length and (2*center[i]-index)>=0 and s[index]==s[2*center[i]-index]: cur+=s[index] index+=1 ccc=cur[::-1] cur=ccc+s[center[i]]+cur if len(cur)>len(maxstr): maxstr=cur i=0 for i in range(length-1): if s[i]==s[i+1] and i not in dc: dc.append(i) if len(dc) !=0: #'aabb'情况 dd=dc[0]+1 cur='' while dd<length and (2*dc[0]+1-dd)>=0 and s[dd]==s[2*dc[0]+1-dd]: cur+=s[dd] dd+=1 ccc=cur[::-1] cur=ccc+cur if len(cur)>len(maxstr): maxstr=cur if len(dc)>1: i=1 for i in range(len(dc)): cur='' dd=dc[i]+1 while dd<length and (2*dc[i]+1-dd)>=0 and s[dd]==s[2*dc[i]+1-dd]: cur+=s[dd] dd+=1 ccc=cur[::-1] cur=ccc+cur if len(cur)>len(maxstr): maxstr=cur return maxstr
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法