↓快轉到主要內容
  1. LeetCode/

LeetCode 1358: Number of Substrings Containing All Three Characters

·1 分鐘· ·
LeetCode Medium Sliding-Window Hash-Table String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-01-19

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

跟 LeetCode 2962 同一個「至少」的計數寫法:三種字元都有時一直縮左邊,縮到少了一種為止,左端在 [0, left) 的子字串都合法,count += left。

我的嘗試
#

第一版用 len(set(s)) 當目標種類數,而不是固定的 3。如果字串本身只有兩種字元,例如 s = "abb",目標變成 2,有 a、b 的子字串都被算進去,回傳 2;但沒有 c 就不可能合法,答案是 0。

正確解法
#

class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        cnt = Counter()
        left = count = 0
        for c in s:
            cnt[c] += 1
            while len(cnt) == 3:                   # 三種都有:一直縮
                cnt[s[left]] -= 1
                if cnt[s[left]] == 0:
                    del cnt[s[left]]
                left += 1
            count += left
        return count

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 目標是固定的 3 種,不是字串裡實際出現的種類數。

面試口說整理
#

這是「至少」型的計數:三種字元都在視窗裡時一直縮左邊,縮到少一種為止,這時左端在 0 到 left - 1 的子字串都包含三種字元,所以加上 left。時間 O(n)。

相關文章

LeetCode 3325: Count Substrings With K-Frequency Characters I
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 3325 解題筆記:「至少一個字元出現 k 次」的計數視窗;剛加入的字元湊滿 k 次就一直縮,縮到它變成 k - 1 次為止
LeetCode 395: Longest Substring with At Least K Repeating Characters
·2 分鐘
LeetCode Medium Sliding-Window Divide-and-Conquer Hash-Table String
LeetCode 395 解題筆記:「每個字元至少 k 次」不單調,不能直接滑動;分治法用出現不到 k 次的字元切開,或枚舉視窗裡有幾種字元,固定種類數後就能滑動
LeetCode 2516: Take K of Each Character From Left and Right
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 2516 解題筆記:從兩端拿等於中間留一段;留下的每種字元最多是總數 − k,找最長的這種中間視窗
LeetCode 1016: Binary String With Substrings Representing 1 To N
·2 分鐘
LeetCode Medium Sliding-Window String Bit-Manipulation Hash-Table
LeetCode 1016 解題筆記:s 最多 1000 個字元,長度固定時的子字串數量有限,n 太大一定是 False;從 n 往下檢查會很快失敗,或從每個起點往右最多延伸 30 位收集所有 <= n 的值
LeetCode 3694: Distinct Points Reachable After Substring Removal
·1 分鐘
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table String
LeetCode 3694 解題筆記:終點 = 全部的位移 − 被刪掉那段的位移;用長度 k 的視窗維護那段的位移,把每個終點放進 set
LeetCode 187: Repeated DNA Sequences
·1 分鐘
LeetCode Medium Hash-Table String Bit-Manipulation Sliding-Window
LeetCode 187 解題筆記:把每個長度 10 的子字串丟進雜湊表計數,出現超過一次的就是答案