# 状态转移方程 P(i,j)=P(i+1,j−1)∧(Si==Sj)
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
if n < 2:
return s
max_len = 1
begin = 0
# dp[i][j] 表示s[i..j]是否是回文串
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True
# 开始递推
# 先枚举子串长度
for L in range(2, n+1):
# 枚举左边界
for i in range(n):
# 由L和i可以确定右边界,即j-i+1 = L
j = L + i - 1
# 如果右边界越界,退出当前循环
if j >= n:
break # 跳出当前循环
if s[i] != s[j]:
dp[i][j] = False
else:
if j-i<3:
dp[i][j] = True
else:
dp[i][j] = dp[i+1][j-1]
# 只要 dp[i][j]==True 成立,就表示子串s[i][j]是回文,此时记录回文长度和起始位置
if dp[i][j] and j-i+1>max_len:
max_len = j-i+1
begin = i
return s[begin:begin+max_len]
最长回文字符串
最新推荐文章于 2024-09-03 21:49:34 发布