leetcode-最长回文子串
题目描述
给你一个字符串 s,找到 s 中最长的回文子串。
示例
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
动态规划
对于一个子串而言,如果它是回文串,并且长度大于 2,那么将它首尾的两个字母去除之后,它仍然是个回文串。例如对于字符串 “ababa”,如果我们已经知道"bab" 是回文串,那么 "ababa" 一定是回文串,这是因为它的首尾两个字母都是"a"。
- 状态定义:dp[i][j]表示s[i...j]是否为回文串
- 转移方程:$dp[i][j] = dp[i+1][j-1] $ and \(s[i]==s[j]\)
- 初始化: \(dp[i][i]=True\), 对角元素为True
- 边界条件:\(j-i<3,dp[i][j] = True\) $(s[i]=s[j]) $
dp[i][j]填表
按列从左至右,自上而下

代码实现
class Solution:
def longestPalindrome(self, s: str) -> str:
'''动态规划
dp[i][j]表示s[i....j]为回文子串
dp[i][j] = dp[i+1][j-1] and s[i]==s[j]
'''
n = len(s)
dp = [[False]*n for _ in range(n)]
if n<2:
return s
# dp初始化
for i in range(n):
dp[i][i] = True
max_sub_str = 1
begin = 0
for j in range(1,n):
for i in range(0,j):
if s[i]==s[j]:
# 边界条件
if j-i<3:
dp[i][j]=True
else:
dp[i][j] = dp[i+1][j-1]
else:
dp[i][j] = False
len_sub_str = j-i+1
# 记录最大回文子串
if dp[i][j] and len_sub_str > max_sub_str:
max_sub_str = len_sub_str
begin = i
end = begin+max_sub_str
return s[begin:end]