LeetCode 题解工作台

包含所有三种字符的子字符串数目

给你一个字符串 s ,它只包含三种字符 a, b 和 c 。 请你返回 a,b 和 c 都 至少 出现过一次的子字符串数目。 示例 1: 输入: s = "abcabc" 输出: 10 解释: 包含 a,b 和 c 各至少一次的子字符串为 " abc ", " abca ", " abcab ", …

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们用一个长度为 的数组 记录三种字符最近一次出现的位置,初始时均为 。 遍历字符串 ,对于当前位置 ,我们先更新 ,然后合法的字符串个数为 $\min(d[0], d[1], d[2]) + 1$,累加到答案中。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 s ,它只包含三种字符 a, b 和 c 。

请你返回 a,b 和 c 都 至少 出现过一次的子字符串数目。

 

示例 1:

输入:s = "abcabc"
输出:10
解释:包含 a,b 和 c 各至少一次的子字符串为 "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc"  "abc" (相同字符串算多次)

示例 2:

输入:s = "aaacb"
输出:3
解释:包含 a,b 和 c 各至少一次的子字符串为 "aaacb", "aacb"  "acb" 。

示例 3:

输入:s = "abc"
输出:1

 

提示:

  • 3 <= s.length <= 5 x 10^4
  • s 只包含字符 a,b 和 c 。
lightbulb

解题思路

方法一:一次遍历

我们用一个长度为 33 的数组 dd 记录三种字符最近一次出现的位置,初始时均为 1-1

遍历字符串 ss,对于当前位置 ii,我们先更新 d[s[i]]=id[s[i]]=i,然后合法的字符串个数为 min(d[0],d[1],d[2])+1\min(d[0], d[1], d[2]) + 1,累加到答案中。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        d = {"a": -1, "b": -1, "c": -1}
        ans = 0
        for i, c in enumerate(s):
            d[c] = i
            ans += min(d["a"], d["b"], d["c"]) + 1
        return ans
speed

复杂度分析

指标
时间complexity is O(n) because we scan the string once, updating last seen indices and computing the minimum each iteration. Space complexity is O(1) since we only store the latest positions of three characters, independent of string length.
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate identifies sliding window as the optimal approach instead of brute force substring checking.

  • question_mark

    Candidate demonstrates correct running state updates for each character and uses minimum index for counting.

  • question_mark

    Candidate maintains O(1) extra space and explains why checking all substrings is unnecessary.

warning

常见陷阱

外企场景
  • error

    Attempting to check every possible substring, resulting in O(n^2) time.

  • error

    Failing to update last seen indices correctly when characters repeat.

  • error

    Counting substrings incorrectly by not considering the minimum last seen position of all three characters.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count substrings containing at least K distinct characters instead of exactly three specific ones.

  • arrow_right_alt

    Extend the problem to larger alphabets beyond 'a', 'b', 'c', requiring dynamic hash table updates.

  • arrow_right_alt

    Compute the longest substring containing all three characters rather than the total number of substrings.

help

常见问题

外企场景

包含所有三种字符的子字符串数目题解:滑动窗口(状态滚动更新) | LeetCode #1358 中等