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

LeetCode 3090: Maximum Length Substring With Two Occurrences

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

基本資料
#

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

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

解題思路
#

視窗合法 ⇔ 每個字元最多出現 2 次。右邊界每加入一個字元,只有這個字元可能超過,所以縮左邊直到它回到 2 次。

LeetCode 2958 是同一題,把 2 換成 k。

我的解法
#

class Solution:
    def maximumLengthSubstring(self, s: str) -> int:
        cnt = Counter()
        left = best = 0
        for right, c in enumerate(s):
            cnt[c] += 1
            while cnt[c] > 2:                      # 只有剛加入的 c 可能超過
                cnt[s[left]] -= 1
                left += 1
            best = max(best, right - left + 1)
        return best

複雜度
#

時間 O(n),空間 O(1)(最多 26 個字元)。

要特別避免的錯誤
#

  • 每次都檢查整個計數表:只有剛加入的字元可能違規。

面試口說整理
#

用求最長的滑動視窗,每個字元最多出現兩次。右邊加入一個字元後,只有它可能超過兩次,所以縮左邊直到它回到兩次,記錄最長長度。時間 O(n)。

相關文章

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 2269: Find the K-Beauty of a Number
·1 分鐘
LeetCode Easy Sliding-Window Math String
LeetCode 2269 解題筆記:把數字轉成字串,枚舉每個長度 k 的子字串;0 不能當除數
LeetCode 2953: Count Complete Substrings
·2 分鐘
LeetCode Hard Sliding-Window Hash-Table String
LeetCode 2953 解題筆記:先在相鄰字元差 > 2 的地方切段;每段枚舉有幾種字元 d,視窗長度固定是 d × k,維護「剛好出現 k 次的字元數」
LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 分鐘
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 解題筆記:要減少種類就得整種刪掉,從出現次數最少的開始刪
LeetCode 3541: Find Most Frequent Vowel and Consonant
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 3541 解題筆記:數每個字元的次數,母音取最大、子音取最大再相加;沒有的那一類算 0
LeetCode 3120: Count the Number of Special Characters I
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 3120 解題筆記:分別收集出現過的小寫和大寫字母,兩個集合的交集大小就是答案