您的位置:首页 > 编程语言 > Python开发

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’的情况。

依次遍历整个字符串,看当前字符左右两边是否相等。

题解:

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 leetcode