给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
示例 3:
输入:s = “a”
输出:“a”
示例 4:
输入:s = “ac”
输出:“a”
中心扩散法
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s)==0:
return 0
if len(s)==1:
return s
cur_len = 0
max_len = 1
max_nums = s[0]
i = 1
j = 0
k = 0
while i < len(s):
if s[i-1] == s[i]:
j = i-2
k = i+1
while j>=0 and k<len(s) and s[j]==s[k]:
j-=1
k+=1
cur_len = k-j-1
if cur_len > max_len:
max_len = cur_len
max_nums = s[j+1,j]
if i!=len(s)-1 and s[i+1] == s[i-1]:
while j>=0 and k<=len(s) and s[j]==s[k]:
j-=1
k+=1
cur_len = k-j-1
if cur_len > max_len:
max_len = cur_len
max_nums = s[j+1,j]
i+=1
return max_len