给定一个字符串 s
,找到 s
中最长的回文子串。你可以假设 s
的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
题解
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
r_i, r_a,tmp_bool = 0, 0, 0
for i in range(len(s)):
a = 0
while 1:
if i - a >= 0 and i + a <= len(s)-1:
if s[i-a] == s[i+a]:
a = a + 1
else:
a = a -1
break
else:
a = a -1
break
if a > r_a:
r_a = a
r_i = i
for i in range(len(s)):
a = 0
while 1:
if i - a >= 0 and i + a+1 <= len(s)-1:
if s[i-a] == s[i+a+1]:
a = a + 1
else:
a = a -1
break
else:
a = a -1
break
if a >= r_a:
r_a = a
r_i = i
tmp_bool = 1
return s[r_i - r_a: r_i+r_a+2] if tmp_bool else s[r_i - r_a: r_i+r_a+1]