LeetCode 题解工作台
拆分字符串使唯一子字符串的数目最大
给你一个字符串 s ,请你拆分该字符串,并返回拆分后唯一子字符串的最大数目。 字符串 s 拆分后可以得到若干 非空子字符串 ,这些子字符串连接后应当能够还原为原字符串。但是拆分出来的每个子字符串都必须是 唯一的 。 注意: 子字符串 是字符串中的一个连续字符序列。 示例 1: 输入: s = "ab…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 回溯·pruning
答案摘要
我们定义一个哈希表 ,用于存储当前已经拆分出的子字符串。然后我们使用深度优先搜索的方式,尝试将字符串 拆分成若干个唯一的子字符串。 具体地,我们设计一个函数 ,表示我们正在考虑将 进行拆分。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路
题目描述
给你一个字符串 s ,请你拆分该字符串,并返回拆分后唯一子字符串的最大数目。
字符串 s 拆分后可以得到若干 非空子字符串 ,这些子字符串连接后应当能够还原为原字符串。但是拆分出来的每个子字符串都必须是 唯一的 。
注意:子字符串 是字符串中的一个连续字符序列。
示例 1:
输入:s = "ababccc" 输出:5 解释:一种最大拆分方法为 ['a', 'b', 'ab', 'c', 'cc'] 。像 ['a', 'b', 'a', 'b', 'c', 'cc'] 这样拆分不满足题目要求,因为其中的 'a' 和 'b' 都出现了不止一次。
示例 2:
输入:s = "aba" 输出:2 解释:一种最大拆分方法为 ['a', 'ba'] 。
示例 3:
输入:s = "aa" 输出:1 解释:无法进一步拆分字符串。
提示:
-
1 <= s.length <= 16 -
s仅包含小写英文字母
解题思路
方法一:回溯 + 剪枝
我们定义一个哈希表 ,用于存储当前已经拆分出的子字符串。然后我们使用深度优先搜索的方式,尝试将字符串 拆分成若干个唯一的子字符串。
具体地,我们设计一个函数 ,表示我们正在考虑将 进行拆分。
在函数 中,我们首先判断如果当前已经拆分出的子字符串的数量加上剩余的字符数小于等于当前的答案,那么我们就没有必要继续拆分,直接返回。如果 ,那么说明我们已经完成了对整个字符串的拆分,我们更新答案为当前的子字符串数量和答案的较大值。否则,我们枚举当前子字符串的结束位置 (不包括 ),并判断 是否已经被拆分出来。如果没有被拆分出来,我们将其加入到哈希表 中,并继续递归地考虑拆分剩余的部分。在递归调用结束后,我们需要将 从哈希表 中移除。
最后,我们返回答案。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def maxUniqueSplit(self, s: str) -> int:
def dfs(i: int):
nonlocal ans
if len(st) + len(s) - i <= ans:
return
if i >= len(s):
ans = max(ans, len(st))
return
for j in range(i + 1, len(s) + 1):
if s[i:j] not in st:
st.add(s[i:j])
dfs(j)
st.remove(s[i:j])
ans = 0
st = set()
dfs(0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n^2 \cdot 2^n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Look for understanding of recursive backtracking and pruning techniques.
- question_mark
Check the candidate's ability to optimize space and time complexity using a set for uniqueness tracking.
- question_mark
Ensure familiarity with managing recursive states and backtracking tree exploration.
常见陷阱
外企场景- error
Forgetting to prune duplicates properly, leading to redundant computations.
- error
Not managing the recursion state efficiently, causing unnecessary recomputation of results.
- error
Misunderstanding the problem requirements, such as assuming substrings can repeat.
进阶变体
外企场景- arrow_right_alt
Limit the length of the substrings (e.g., substrings must be at least 2 characters long).
- arrow_right_alt
Extend the problem to work with strings containing uppercase letters or non-alphabetical characters.
- arrow_right_alt
Change the problem to return the substrings instead of their count, requiring a different approach.