leetcode5-最长回文子串
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
算法设计:
遍历字符串s,以当前点i为中点向两端遍历;记录中心点i的回文字符串左右标记l,r;计算长度更新长度大于以前遍历的l,r端点;遍历完后返回s[l:r].
源代码:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# edge case
if len(s) == 0:
return
if len(s) == 1:
return s[0]
# init result
result = ""
for i in range(0, len(s) - 1):
tmp = self.helper(s, i, i) # odd case
if len(result) < len(tmp):
result = tmp
tmp = self.helper(s, i, i + 1) # even case
if len(result) < len(tmp):
result = tmp
return result
def helper(self, s, i, j):
r = i
c = j
tmp = ""
while s[r] == s[c]:
if r != c:
tmp = s[r] + tmp + s[c]
else:
tmp = s[r] #odd case
r = r - 1
c = c + 1
if r < 0 or c > len(s) - 1:
return tmp
return tmp