https://leetcode.cn/problems/longest-palindromic-substring/
给你一个字符串 s,找到 s 中最长的回文子串。
如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
class Solution:
def longestPalindrome(self, s: str) -> str:
# 双指针、中心扩展
def huiwen(strs, left, right):
while left >= 0 and right < len(strs) and strs[left] == strs[right]:
left -= 1
right += 1
return left + 1, right - left - 1
start, maxlength = 0, 0
for i in range(len(s)):
start1, length1 = huiwen(s, i, i)
strat2, length2 = huiwen(s, i, i + 1)
if length1 > maxlength:
start = start1
maxlength = length1
if length2 > maxlength:
start = strat2
maxlength = length2
return s[start: start + maxlength]
# 暴力搜索、勉强通过
# n = len(s)
# ret = ''
# for i in range(n):
# for j in range(i + 1, n + 1):
# if s[i:j] == s[i:j][::-1] and (j - i + 1) > len(ret):
# ret = s[i:j]
# return ret