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"
分析:
遍历数组,判断以每个字符为中心分别向两头扩散,是否为回文序列。根据回文的长度分两种情况:偶数回文和奇数回文。
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
res = ''
for i in range(len(s)):
# odd case, like 'aba'
tmp = self.helper(s, i, i)
if len(tmp) > len(res):
res = tmp
# even case, like 'abba'
tmp = self.helper(s, i, i+1)
if len(tmp) > len(res):
res = tmp
return res
def helper(self, s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
return s[l+1:r]