leetcode第5道题,
题目如下:
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.
题目解释:给定一个字符串S,找出最长的回文子串
这里提供两种解法:
1.最原始的做法,一个一个挑出子字符串判定是否为回文字符串(能实现,但超时了)
class Solution(object):
#思路:逐一比较子串,找出最长回文子串
#判断是否是回文字符
def isPalind(self,ss,start,end):
while start < end:
if ss[start] != ss[end]:
return False
start += 1
end -= 1
return True
def longestPalindrome(self, s): #这个不就是先固定i,在依次移动右边位置,依次比较的嘛
len_s = len(s)
max_s,left,right = 0, 0, 0
for i in range(len_s):
j = i + 1
while j < len_s:
if self.isPalind(s, i, j):
if (j -i + 1) > max_s:
left,right = i, j
max_s = j - i + 1
j += 1
return s[left : right + 1]
2. 双指针两边扩展法
class Solution(object):
def longestPalindrome(self, s):
#思路:双指针两边扩展,一往左,一往右,找相等
# maxr,maxl,maxs = 0,0,0
m1,m2,maxs = 0,0,0
n = len(s)
for i in range(n):
#当回文字符串长度为偶数时,中间的相邻等,然后分别往左右扩展
maxl = i
maxr = i + 1
while maxl >= 0 and maxr < n:
if s[maxl] == s[maxr]:
if (maxr - maxl + 1) > maxs:
m1 ,m2 = maxl, maxr
maxs = maxr - maxl + 1
maxl -= 1
maxr += 1
else:
break
#当回文字符串长度为奇数时,中间三数间隔为1等,再分别左右扩展
maxl = i - 1
maxr = i + 1
while maxl >=0 and maxr < n:
if s[maxl] == s[maxr]:
if (maxr - maxl + 1) > maxs:
m1 ,m2 = maxl, maxr
maxs = maxr - maxl + 1
maxl -= 1
maxr += 1
else:
break
return s[m1 : m2 + 1]