LeetCode 题解工作台
分割回文串 IV
给你一个字符串 s ,如果可以将它分割成三个 非空 回文子字符串,那么返回 true ,否则返回 false 。 当一个字符串正着读和反着读是一模一样的,就称其为 回文字符串 。 示例 1: 输入: s = "abcbdd" 输出: true 解释: "abcbdd" = "a" + "bcb" +…
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示字符串 的第 个字符到第 个字符是否为回文串,初始时 $f[i][j] = \textit{true}$。 然后我们可以通过以下的状态转移方程来计算 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s ,如果可以将它分割成三个 非空 回文子字符串,那么返回 true ,否则返回 false 。
当一个字符串正着读和反着读是一模一样的,就称其为 回文字符串 。
示例 1:
输入:s = "abcbdd" 输出:true 解释:"abcbdd" = "a" + "bcb" + "dd",三个子字符串都是回文的。
示例 2:
输入:s = "bcbddxy" 输出:false 解释:s 没办法被分割成 3 个回文子字符串。
提示:
3 <= s.length <= 2000s 只包含小写英文字母。
解题思路
方法一:动态规划
我们定义 表示字符串 的第 个字符到第 个字符是否为回文串,初始时 。
然后我们可以通过以下的状态转移方程来计算 :
由于 依赖于 ,因此,我们需要从大到小的顺序枚举 ,从小到大的顺序枚举 ,这样才能保证当计算 时 已经被计算过。
接下来,我们枚举第一个子串的右端点 ,第二个子串的右端点 ,那么第三个子串的左端点可以枚举的范围为 ,其中 是字符串 的长度。如果第一个子串 、第二个子串 和第三个子串 都是回文串,那么我们就找到了一种可行的分割方案,返回 。
枚举完所有的分割方案后,如果没有找到符合要求的分割方案,那么返回 。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
class Solution:
def checkPartitioning(self, s: str) -> bool:
n = len(s)
f = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
f[i][j] = s[i] == s[j] and (i + 1 == j or f[i + 1][j - 1])
for i in range(n - 2):
for j in range(i + 1, n - 1):
if f[0][i] and f[i + 1][j] and f[j + 1][-1]:
return True
return False
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate efficiently preprocess palindrome checks in O(1) time for each substring?
- question_mark
Does the candidate understand the importance of dynamic programming for breaking down the problem into smaller subproblems?
- question_mark
Can the candidate discuss trade-offs in time and space complexity for this problem?
常见陷阱
外企场景- error
Forgetting to preprocess palindrome checks, leading to inefficient solutions with redundant checks.
- error
Overcomplicating the dynamic programming approach by not leveraging the preprocessed palindrome table.
- error
Not correctly handling edge cases, such as strings that cannot be split into three palindromes.
进阶变体
外企场景- arrow_right_alt
Generalize the problem by allowing a different number of palindromic substrings (e.g., 2 or 4 substrings).
- arrow_right_alt
Extend the problem to handle a larger input size or strings with uppercase characters.
- arrow_right_alt
Optimize the solution further by reducing the space complexity of the palindrome check table.