题目地址: 链接
状态转移方程:
d p i j = { 1 , 当 i = j (单个字符,必然是回文,长度为1) 2 , 当 j − i = 1 且 s i = s j (两个相同字符,回文长度为2) d p i + 1 j − 1 + 2 , 当 j − i ≥ 2 且 s i = s j 且 d p i + 1 j − 1 > 0 (长串回文依赖内部子串) dpij = \begin{cases} 1, & \text{当 } i = j \text{(单个字符,必然是回文,长度为1)} \\ 2, & \text{当 } j - i = 1 \text{ 且 } si = sj \text{(两个相同字符,回文长度为2)} \\ dpi+1j-1 + 2, & \text{当 } j - i \ge 2 \text{ 且 } si = sj \text{ 且 } dpi+1j-1 > 0 \text{(长串回文依赖内部子串)} \end{cases} dpij=⎩ ⎨ ⎧1,2,dpi+1j−1+2,当 i=j(单个字符,必然是回文,长度为1)当 j−i=1 且 si=sj(两个相同字符,回文长度为2)当 j−i≥2 且 si=sj 且 dpi+1j−1>0(长串回文依赖内部子串)
js
/*
* @lc app=leetcode.cn id=5 lang=typescript
*
* [5] 最长回文子串
*/
// @lc code=start
function longestPalindrome(s: string): string {
const n = s.length;
const dp = Array.from({length: n + 1}, () => new Array(n + 1).fill(0));
let maxLen = 1;
let ans = s[0];
for(let step = 0; step < n; step ++) {
for(let i = 0; i < n - step; i ++) {
let j = i + step;
if(s[j] == s[i]) {
if(j == i) dp[i][j] = 1;
if(j - i == 1) dp[i][j] = 2;
if(j - i >= 2 && dp[i + 1][j - 1]) {
dp[i][j] = dp[i + 1][j - 1] + 2;
}
}
if(maxLen < dp[i][j]) {
maxLen = Math.max(maxLen, dp[i][j]);
ans = s.slice(i, j + 1);
}
}
}
return ans;
};
// dp[0][3] = dp[1][2] + 2, if s[0] == s[3]
// dp[0][1] = 2, if s[0] == s[1]
// dp[0][0] = 1, (s[0] 一定等于 s[0], 单个字符一定是回文串)
// dp[i][i] = 1
// dp[i][i + 1] = 2, if s[i] == s[i + 1]
// dp[i][j] = dp[i + 1][j - 1] + 2, if s[i] == s[j]
// @lc code=end