LeetCode 题解工作台
最长回文子串
给你一个字符串 s ,找到 s 中最长的 回文 子串 。 示例 1: 输入: s = "babad" 输出: "bab" 解释: "aba" 同样是符合题意的答案。 示例 2: 输入: s = "cbbd" 输出: "bb" 提示: 1 s 仅由数字和英文字母组成
3
题型
11
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示字符串 是否为回文串,初始时 $f[i][j] = true$。 接下来,我们定义变量 和 ,其中 表示最长回文串的起始位置, 表示最长回文串的长度。初始时 $k = 0$, $mx = 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s,找到 s 中最长的 回文 子串。
示例 1:
输入:s = "babad" 输出:"bab" 解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd" 输出:"bb"
提示:
1 <= s.length <= 1000s仅由数字和英文字母组成
解题思路
方法一:动态规划
我们定义 表示字符串 是否为回文串,初始时 。
接下来,我们定义变量 和 ,其中 表示最长回文串的起始位置, 表示最长回文串的长度。初始时 , 。
考虑 ,如果 ,那么 ;否则 。如果 并且 ,那么我们更新 , 。
由于 依赖于 ,因此我们需要保证 在 之前,因此我们需要从大到小地枚举 ,从小到大地枚举 。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
f = [[True] * n for _ in range(n)]
k, mx = 0, 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
f[i][j] = False
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1]
if f[i][j] and mx < j - i + 1:
k, mx = i, j - i + 1
return s[k : k + mx]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Do you identify both odd and even length palindromes during center expansion?
- question_mark
Can you explain how previously computed palindromes reduce redundant checks in the DP table?
- question_mark
Will you update the longest palindrome tracking correctly when multiple candidates of the same length exist?
常见陷阱
外企场景- error
Forgetting to check even-length palindromes, which requires treating centers between characters.
- error
Not initializing DP base cases correctly, leading to incorrect longer palindrome computation.
- error
Expanding beyond string bounds when checking centers, causing runtime errors.
进阶变体
外企场景- arrow_right_alt
Find the number of distinct palindromic substrings in a given string.
- arrow_right_alt
Return the longest palindromic subsequence instead of substring, allowing non-contiguous characters.
- arrow_right_alt
Compute the longest palindrome in a streaming string with limited memory, requiring on-the-fly updates.