题目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
代码:
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
left = right = 0 #记录最长回文串的上下标
lens = 0 #记录最长回文串长度
for i in range(n) : #遍历每一个元素,以该元素为中心,左右两边扩展查找最长的回文串
len1 = self.GetPalindrome(s, i, i) #计算aba型的回文串长度
len2 = self.GetPalindrome(s, i, i+1) #计算abba型的回文串长度
if lens < max(len1, len2) : #如果有更长的回文串,更新left和right的值
if len1 >= len2 : #确定是aba型还是abba型,以方便更新left和right的值
left = i - len1/2
right = i + len1/2
lens = len1
else :
left = i - len2/2 + 1
right = i + len2/2
lens = len2
return s[left:right+1] #返回找到的最长回文串
def GetPalindrome(self, s, start, end): #以start开头, end结尾的位置在s中扩展查找回文串
m = len(s)
i = start
j = end
while i >= 0 and j < m and s[i] == s[j] : #向两边扩展搜索最长回文串
i -= 1
j += 1
return j-i-1 #返回找到的回文串长度