5. 最长回文子串
题目描述
给你一个字符串 s,找到 s 中最长的回文子串。
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
if n < 2:
return s
mlen = 1
mbegin = 0
dp = [[False]*n for _ in range(n)]
for i in range(n):
dp[i][i] = True
for L in range(2, n + 1):
for l in range(n):
r = l + L - 1
if r >= n:
break
if s[l] != s[r]:
dp[l][r] = False
else:
if L <= 3:
dp[l][r] = True
else:
dp[l][r] = dp[l+1][r-1]
if dp[l][r] and L > mlen:
mlen = L
mbegin = l
return s[mbegin: mbegin + mlen]
思路:
dp数组维护左边界为l,右边界为r的字串是否为回文串,先对长度遍历,再对左边界遍历,计算右边界。