要求
给你一个字符串 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:
max_l = 0
res = ""
for i in range(0,len(s)):
for j in range(i,len(s)):
substring = s[i:j + 1]
if substring == substring[::-1]:
if max_l < j + 1 - i:
max_l = j + 1 - i
res = substring
return res
核心代码
class Solution:
def longestPalindrome(self, s: str) -> str:
max_l = 0
res = ""
for i in range(0,len(s)):
# 以s[i]为中心向左右扩散
left,right = i,i
while (left >= 0 and right < len(s) and s[left] == s[right]):
if max_l < right -left + 1:
max_l = right -left + 1
res = s[left:right + 1]
left -= 1
right += 1
# 以s[i],s[i+1]为中心向左右扩散
left,right = i,i + 1
while (left >= 0 and right < len(s) and s[left] == s[right]):
if max_l < right -left + 1:
max_l = right -left + 1
res = s[left:right + 1]
left -= 1
right += 1
return res
重点问题
解题思路:
第一种解法:直接得到所有的字串,然后进行判断,但是会超时,第二种解法:从中心向外展开,我们需要搞清楚两种情况,第一种"bab",第二种"baab",所以出现两种情况的中心扩散。