LeetCode 题解工作台
分割字符串
给你一个字符串 s ,按照以下步骤将其分割为 互不相同的段 : 从下标 0 开始构建一个段。 逐字符扩展当前段,直到该段之前未曾出现过。 只要当前段是唯一的,就将其加入段列表,标记为已经出现过,并从下一个下标开始构建新的段。 重复上述步骤,直到处理完整个字符串 s 。 返回字符串数组 segment…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 哈希·表·结合·string
答案摘要
我们可以用一个哈希表 来记录已经出现过的段。然后我们遍历字符串 ,逐字符构建当前段 ,直到该段之前未曾出现过。每当我们构建出一个新的段时,就将其加入到结果列表中,并将其标记为已经出现过。 遍历结束后,返回结果列表即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个字符串 s,按照以下步骤将其分割为 互不相同的段 :
- 从下标 0 开始构建一个段。
- 逐字符扩展当前段,直到该段之前未曾出现过。
- 只要当前段是唯一的,就将其加入段列表,标记为已经出现过,并从下一个下标开始构建新的段。
- 重复上述步骤,直到处理完整个字符串
s。
返回字符串数组 segments,其中 segments[i] 表示创建的第 i 段。
示例 1:
输入: s = "abbccccd"
输出: ["a","b","bc","c","cc","d"]
解释:
| 下标 | 添加后的段 | 已经出现过的段 | 当前段是否已经出现过? | 新段 | 更新后已经出现过的段 |
|---|---|---|---|---|---|
| 0 | "a" | [] | 否 | "" | ["a"] |
| 1 | "b" | ["a"] | 否 | "" | ["a", "b"] |
| 2 | "b" | ["a", "b"] | 是 | "b" | ["a", "b"] |
| 3 | "bc" | ["a", "b"] | 否 | "" | ["a", "b", "bc"] |
| 4 | "c" | ["a", "b", "bc"] | 否 | "" | ["a", "b", "bc", "c"] |
| 5 | "c" | ["a", "b", "bc", "c"] | 是 | "c" | ["a", "b", "bc", "c"] |
| 6 | "cc" | ["a", "b", "bc", "c"] | 否 | "" | ["a", "b", "bc", "c", "cc"] |
| 7 | "d" | ["a", "b", "bc", "c", "cc"] | 否 | "" | ["a", "b", "bc", "c", "cc", "d"] |
因此,最终输出为 ["a", "b", "bc", "c", "cc", "d"]。
示例 2:
输入: s = "aaaa"
输出: ["a","aa"]
解释:
| 下标 | 添加后的段 | 已经出现过的段 | 当前段是否已经出现过? | 新段 | 更新后已经出现过的段 |
|---|---|---|---|---|---|
| 0 | "a" | [] | 否 | "" | ["a"] |
| 1 | "a" | ["a"] | 是 | "a" | ["a"] |
| 2 | "aa" | ["a"] | 否 | "" | ["a", "aa"] |
| 3 | "a" | ["a", "aa"] | 是 | "a" | ["a", "aa"] |
因此,最终输出为 ["a", "aa"]。
提示:
1 <= s.length <= 105s仅包含小写英文字母。
解题思路
方法一:哈希表 + 模拟
我们可以用一个哈希表 来记录已经出现过的段。然后我们遍历字符串 ,逐字符构建当前段 ,直到该段之前未曾出现过。每当我们构建出一个新的段时,就将其加入到结果列表中,并将其标记为已经出现过。
遍历结束后,返回结果列表即可。
时间复杂度 ,空间复杂度 ,其中 是字符串 的长度。
class Solution:
def partitionString(self, s: str) -> List[str]:
vis = set()
ans = []
t = ""
for c in s:
t += c
if t not in vis:
vis.add(t)
ans.append(t)
t = ""
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Does the candidate understand how to handle string segmentation efficiently?
- question_mark
Is the candidate able to manage a hash table for tracking characters in real-time?
- question_mark
Can the candidate explain the trade-offs involved in choosing hash tables over other data structures?
常见陷阱
外企场景- error
Not properly managing the segments when characters repeat, leading to incorrect partitions.
- error
Using a brute force approach with nested loops, which results in higher time complexity.
- error
Failing to handle edge cases like strings with all unique characters or all repeated characters.
进阶变体
外企场景- arrow_right_alt
Modify the problem to use uppercase letters only.
- arrow_right_alt
Extend the problem to allow a custom rule for segment uniqueness, such as allowing certain characters to repeat a limited number of times.
- arrow_right_alt
Solve the problem with a Trie data structure instead of a hash table.