LeetCode 题解工作台
不重叠回文子字符串的最大数目
给你一个字符串 s 和一个 正 整数 k 。 从字符串 s 中选出一组满足下述条件且 不重叠 的子字符串: 每个子字符串的长度 至少 为 k 。 每个子字符串是一个 回文串 。 返回最优方案中能选择的子字符串的 最大 数目。 子字符串 是字符串中一个连续的字符序列。 示例 1 : 输入: s = "…
4
题型
4
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
预处理字符串 ,得到 表示字符串 是否为回文串。 然后定义函数 表示从字符串 中选出最多的不重叠回文子串的个数,即:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s 和一个 正 整数 k 。
从字符串 s 中选出一组满足下述条件且 不重叠 的子字符串:
- 每个子字符串的长度 至少 为
k。 - 每个子字符串是一个 回文串 。
返回最优方案中能选择的子字符串的 最大 数目。
子字符串 是字符串中一个连续的字符序列。
示例 1 :
输入:s = "abaccdbbd", k = 3 输出:2 解释:可以选择 s = "abaccdbbd" 中斜体加粗的子字符串。"aba" 和 "dbbd" 都是回文,且长度至少为 k = 3 。 可以证明,无法选出两个以上的有效子字符串。
示例 2 :
输入:s = "adbcda", k = 2 输出:0 解释:字符串中不存在长度至少为 2 的回文子字符串。
提示:
1 <= k <= s.length <= 2000s仅由小写英文字母组成
解题思路
方法一:预处理 + 记忆化搜索
预处理字符串 ,得到 表示字符串 是否为回文串。
然后定义函数 表示从字符串 中选出最多的不重叠回文子串的个数,即:
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def maxPalindromes(self, s: str, k: int) -> int:
@cache
def dfs(i):
if i >= n:
return 0
ans = dfs(i + 1)
for j in range(i + k - 1, n):
if dp[i][j]:
ans = max(ans, 1 + dfs(j + 1))
return ans
n = len(s)
dp = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
dp[i][j] = s[i] == s[j] and dp[i + 1][j - 1]
ans = dfs(0)
dfs.cache_clear()
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate efficiently applies dynamic programming to solve the problem.
- question_mark
Demonstrates understanding of state transitions and two-pointer technique.
- question_mark
Can identify and optimize the problem by carefully considering substring overlap.
常见陷阱
外企场景- error
Failing to efficiently check for palindromes, leading to a slow solution.
- error
Not ensuring non-overlapping substrings, causing incorrect selections.
- error
Overcomplicating the dynamic programming approach without considering time complexity.
进阶变体
外企场景- arrow_right_alt
Modify the problem by requiring palindromic substrings to be of an exact length, not just at least k.
- arrow_right_alt
Limit the total number of palindromic substrings to a fixed number.
- arrow_right_alt
Extend the problem to handle uppercase letters or non-ASCII characters.