LeetCode 题解工作台
字符至少出现 K 次的子字符串 I
给你一个字符串 s 和一个整数 k ,在 s 的所有子字符串中,请你统计并返回 至少有一个 字符 至少出现 k 次的子字符串总数。 子字符串 是字符串中的一个连续、 非空 的字符序列。 示例 1: 输入: s = "abacb", k = 2 输出: 4 解释: 符合条件的子字符串如下: "aba"…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们可以枚举子字符串的右端点,然后用一个滑动窗口维护子字符串的左端点,使得滑动窗口内的子字符串中的每个字符出现次数都小于 。 我们可以用一个数组 维护滑动窗口内的每个字符的出现次数,然后用一个变量 维护滑动窗口的左端点,用一个变量 维护答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个字符串 s 和一个整数 k,在 s 的所有子字符串中,请你统计并返回 至少有一个 字符 至少出现 k 次的子字符串总数。
子字符串 是字符串中的一个连续、 非空 的字符序列。
示例 1:
输入: s = "abacb", k = 2
输出: 4
解释:
符合条件的子字符串如下:
"aba"(字符'a'出现 2 次)。"abac"(字符'a'出现 2 次)。"abacb"(字符'a'出现 2 次)。"bacb"(字符'b'出现 2 次)。
示例 2:
输入: s = "abcde", k = 1
输出: 15
解释:
所有子字符串都有效,因为每个字符至少出现一次。
提示:
1 <= s.length <= 30001 <= k <= s.lengths仅由小写英文字母组成。
解题思路
方法一:滑动窗口
我们可以枚举子字符串的右端点,然后用一个滑动窗口维护子字符串的左端点,使得滑动窗口内的子字符串中的每个字符出现次数都小于 。
我们可以用一个数组 维护滑动窗口内的每个字符的出现次数,然后用一个变量 维护滑动窗口的左端点,用一个变量 维护答案。
当我们枚举右端点时,我们可以将右端点的字符加入滑动窗口,然后判断滑动窗口内右端点的字符出现次数是否大于等于 ,如果是,则将左端点的字符移出滑动窗口,直到滑动窗口内的每个字符出现次数都小于 。此时,对于左端点为 ,且右端点为 的子字符串,都满足题目要求,因此答案加上 。
枚举结束后,返回答案即可。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 ,其中 是字符集,这里是小写字母集合,因此 。
class Solution:
def numberOfSubstrings(self, s: str, k: int) -> int:
cnt = Counter()
ans = l = 0
for c in s:
cnt[c] += 1
while cnt[c] >= k:
cnt[s[l]] -= 1
l += 1
ans += l
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) in the worst case due to nested left-right iterations but often performs better with early stopping. Space complexity is O(1) or O(26) for the fixed alphabet hash map. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask about edge cases where k is larger than substring length.
- question_mark
Check if the candidate correctly maintains character counts in the sliding window.
- question_mark
Expect recognition of early stopping to avoid unnecessary substring checks.
常见陷阱
外企场景- error
Not updating the frequency map correctly when moving the left index.
- error
Counting substrings multiple times by not fixing the left index properly.
- error
Assuming all characters must appear k times instead of at least one.
进阶变体
外企场景- arrow_right_alt
Count substrings where exactly one character appears k times.
- arrow_right_alt
Find the longest substring where at least one character frequency is at least k.
- arrow_right_alt
Apply the same method to strings with uppercase letters or digits, adjusting the hash map.