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

LeetCode 3258: Count Substrings That Satisfy K-Constraint I

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

基本資料
#

難易度: easy 第一次嘗試:2026-01-18

  • 提交紀錄:Accepted(一次通過)

解題思路
#

合法 ⇔ 0 的個數 <= k 或 1 的個數 <= k。反過來,不合法 ⇔ 兩個都 > k。

視窗變大時兩個計數都不會變少,所以「不合法」是單調的:

  • 右端加入字元,兩個都 > k 就縮左邊。
  • 以 right 結尾的合法子字串有 right - left + 1 個(左端在 [left, right] 的都合法)。

我的解法
#

class Solution:
    def countKConstraintSubstrings(self, s: str, k: int) -> int:
        cnt = Counter()
        left = count = 0
        for right, c in enumerate(s):
            cnt[c] += 1
            while cnt["0"] > k and cnt["1"] > k:
                cnt[s[left]] -= 1
                left += 1
            count += right - left + 1
        return count

複雜度
#

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

要特別避免的錯誤
#

  • 縮視窗的條件寫成 or:只要有一個 <= k 就合法,兩個都超過才要縮。

面試口說整理
#

子字串合法的條件是 0 或 1 其中一個不超過 k,所以兩個都超過才不合法,這個條件是單調的。我用滑動視窗,兩個都超過就縮左邊,以右端結尾的合法子字串有 right - left + 1 個,全部加起來。時間 O(n)。

相關文章

LeetCode 3090: Maximum Length Substring With Two Occurrences
·1 分鐘
LeetCode Easy Sliding-Window Hash-Table String
LeetCode 3090 解題筆記:「求最長」的滑動視窗,剛加進來的字元超過 2 次就縮左邊
LeetCode 1763: Longest Nice Substring
·1 分鐘
LeetCode Easy Sliding-Window Divide-and-Conquer Hash-Table String Bit-Manipulation
LeetCode 1763 解題筆記:沒有大小寫配對的字元一定不在答案裡,用它切開字串遞迴;長度相同時取左邊的
LeetCode 2269: Find the K-Beauty of a Number
·1 分鐘
LeetCode Easy Sliding-Window Math String
LeetCode 2269 解題筆記:把數字轉成字串,枚舉每個長度 k 的子字串;0 不能當除數
LeetCode 1234: Replace the Substring for Balanced String
·1 分鐘
LeetCode Medium Sliding-Window String
LeetCode 1234 解題筆記:替換一段之後,視窗外的每個字元都不能超過 n / 4;用「求最短」的滑動視窗維護視窗外的數量
LeetCode 3813: Vowel-Consonant Score
·1 分鐘
LeetCode Easy String Simulation
LeetCode 3813 解題筆記:只數字母,分成母音和子音;子音是 0 時分數是 0,否則用整數除法
LeetCode 2730: Find the Longest Semi-Repetitive Substring
·1 分鐘
LeetCode Medium Sliding-Window String
LeetCode 2730 解題筆記:視窗裡最多一組相鄰相同的數字;新的一組進來就縮左邊,直到移出前一組