LeetCode 题解工作台

字符至少出现 K 次的子字符串 I

给你一个字符串 s 和一个整数 k ,在 s 的所有子字符串中,请你统计并返回 至少有一个 字符 至少出现 k 次的子字符串总数。 子字符串 是字符串中的一个连续、 非空 的字符序列。 示例 1: 输入: s = "abacb", k = 2 输出: 4 解释: 符合条件的子字符串如下: "aba"…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们可以枚举子字符串的右端点,然后用一个滑动窗口维护子字符串的左端点,使得滑动窗口内的子字符串中的每个字符出现次数都小于 。 我们可以用一个数组 维护滑动窗口内的每个字符的出现次数,然后用一个变量 维护滑动窗口的左端点,用一个变量 维护答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 <= 3000
  • 1 <= k <= s.length
  • s 仅由小写英文字母组成。
lightbulb

解题思路

方法一:滑动窗口

我们可以枚举子字符串的右端点,然后用一个滑动窗口维护子字符串的左端点,使得滑动窗口内的子字符串中的每个字符出现次数都小于 kk

我们可以用一个数组 cnt\textit{cnt} 维护滑动窗口内的每个字符的出现次数,然后用一个变量 l\textit{l} 维护滑动窗口的左端点,用一个变量 ans\textit{ans} 维护答案。

当我们枚举右端点时,我们可以将右端点的字符加入滑动窗口,然后判断滑动窗口内右端点的字符出现次数是否大于等于 kk,如果是,则将左端点的字符移出滑动窗口,直到滑动窗口内的每个字符出现次数都小于 kk。此时,对于左端点为 [0,..l1][0, ..l - 1],且右端点为 rr 的子字符串,都满足题目要求,因此答案加上 ll

枚举结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(Σ)O(|\Sigma|),其中 Σ\Sigma 是字符集,这里是小写字母集合,因此 Σ=26|\Sigma| = 26

1
2
3
4
5
6
7
8
9
10
11
12
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

字符至少出现 K 次的子字符串 I题解:滑动窗口(状态滚动更新) | LeetCode #3325 中等