最长回文子串
描述
class Solution(object):
def longestPalindrome(self, s):
if len(s) == 1 or (len(s) == 2 and self.isPalindrome(s)):
return s
max_sub = ""
for i in range(len(s)):
sub1 = self.thelongestPalindrome(s,i,i) # 回文中心为一个字符的情况
sub2 = self.thelongestPalindrome(s,i,i+1) # 回文中心为两个字符的情况
if len(sub1)>len(sub2) and len(sub1)>len(max_sub):
max_sub = sub1
if len(sub2)>len(sub1) and len(sub2)>len(max_sub):
max_sub = sub2
if len(max_sub)>len(s)/2:
return max_sub
return max_sub
def thelongestPalindrome(self, s, left, right):
max_sub = ""
while left>=0 and right < len(s):
sub = s[left:right+1]
if left==right or s[left]==s[right]:
max_sub = sub
left-=1
right+=1
else:
break
return max_sub
def isPalindrome(self, s):
length = len(s)
for i in range(int(length / 2)):
if not s[i] == s[length - 1 - i]:
return False
return True