LeetCode 题解工作台
子字符串的最优划分
给你一个字符串 s ,请你将该字符串划分成一个或多个 子字符串 ,并满足每个子字符串中的字符都是 唯一 的。也就是说,在单个子字符串中,字母的出现次数都不超过 一次 。 满足题目要求的情况下,返回 最少 需要划分多少个子字符串 。 注意,划分后,原字符串中的每个字符都应该恰好属于一个子字符串。 示例…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
根据题意,每个子字符串应该尽可能长,且包含的字符唯一,因此,我们只需要贪心地进行划分即可。 我们定义一个二进制整数 来记录当前子字符串中出现的字符,其中 的第 位为 表示第 个字母已经出现过,为 表示未出现过。另外,我们还需要一个变量 来记录划分的子字符串个数,初始时 $\textit{ans} = 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个字符串 s ,请你将该字符串划分成一个或多个 子字符串 ,并满足每个子字符串中的字符都是 唯一 的。也就是说,在单个子字符串中,字母的出现次数都不超过 一次 。
满足题目要求的情况下,返回 最少 需要划分多少个子字符串。
注意,划分后,原字符串中的每个字符都应该恰好属于一个子字符串。
示例 1:
输入:s = "abacaba"
输出:4
解释:
两种可行的划分方法分别是 ("a","ba","cab","a") 和 ("ab","a","ca","ba") 。
可以证明最少需要划分 4 个子字符串。
示例 2:
输入:s = "ssssss"
输出:6
解释:
只存在一种可行的划分方法 ("s","s","s","s","s","s") 。
提示:
1 <= s.length <= 105s仅由小写英文字母组成
解题思路
方法一:贪心
根据题意,每个子字符串应该尽可能长,且包含的字符唯一,因此,我们只需要贪心地进行划分即可。
我们定义一个二进制整数 来记录当前子字符串中出现的字符,其中 的第 位为 表示第 个字母已经出现过,为 表示未出现过。另外,我们还需要一个变量 来记录划分的子字符串个数,初始时 。
遍历字符串 中的每个字符,对于每个字符 ,我们将其转换为 到 之间的整数 ,然后判断 的第 位是否为 ,如果为 ,说明当前字符 与当前子字符串中的字符有重复,此时 需要加 ,并将 置为 ;否则,将 的第 位置为 。然后,我们将 更新为 与 的按位或结果。
最后,返回 即可。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def partitionString(self, s: str) -> int:
ans, mask = 1, 0
for x in map(lambda c: ord(c) - ord("a"), s):
if mask >> x & 1:
ans += 1
mask = 0
mask |= 1 << x
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate identify and implement a greedy solution to handle substrings with unique characters?
- question_mark
Does the candidate consider edge cases in the problem, such as all characters being the same or all characters being unique?
- question_mark
Is the candidate able to explain how set operations play a role in partitioning the string?
常见陷阱
外企场景- error
Failing to handle strings with all unique or all same characters properly.
- error
Misunderstanding the need to track only unique characters within each substring.
- error
Not using an efficient data structure like a set to track characters within the substring.
进阶变体
外企场景- arrow_right_alt
What if the string contains digits instead of lowercase letters?
- arrow_right_alt
Can the algorithm handle uppercase letters or a mixture of uppercase and lowercase?
- arrow_right_alt
How would you adapt this solution for strings with a larger character set, like Unicode characters?