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

LeetCode 1156: Swap For Longest Repeated Character Substring

·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-23

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

解題思路
#

最多交換一次,最後的連續段是某個字元 c。對每個 c 分別處理:

  • 找最多只有一個字元不是 c 的最長視窗,那個字元可以跟別處的 c 交換。
  • 但換進來的 c 必須來自視窗外。如果所有的 c 都已經在視窗裡,就沒有 c 可以換進來,只能把視窗邊上的 c 移到中間,長度是 c 的總數。
  • 所以這個 c 的答案是 min(視窗長度, total[c])。

最多 26 種字元,每種一次 O(n) 的滑動視窗。

我的解法
#

class Solution:
    def maxRepOpt1(self, text: str) -> int:
        total = Counter(text)
        best = 0
        for c in total:
            left = other = 0
            for right, ch in enumerate(text):
                other += ch != c
                while other > 1:                   # 最多一個不是 c
                    other -= text[left] != c
                    left += 1
                best = max(best, min(right - left + 1, total[c]))
        return best

複雜度
#

時間 O(26 · n),空間 O(26)。

要特別避免的錯誤
#

  • 忘了長度上限是 c 的總數:例如 "aaabaaa" 只有 6 個 a,答案是 6 不是 7。

面試口說整理
#

最後的連續段是某個字元 c,所以我對每個字元找最多一個不是 c 的最長視窗,那一個可以跟別處的 c 交換。但換進來的 c 要來自別處,所以長度不能超過 c 的總數,取兩者的較小值。26 個字元各一次滑動視窗,O(26n)。

相關文章

LeetCode 3306: Count of Substrings Containing Every Vowel and K Consonants II
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 3306 解題筆記:「剛好 k 個子音」不單調;改成「五個母音都有且子音至少 k 個」減「至少 k + 1 個」,兩個都是「至少」型的計數視窗
LeetCode 1358: Number of Substrings Containing All Three Characters
·1 分鐘
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 1358 解題筆記:「至少各一個 a、b、c」的計數視窗:三種都有時一直縮左邊,count += left
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 的值