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

LeetCode 424: Longest Repeating Character Replacement

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

基本資料
#

難易度: medium 第一次嘗試:2022-10-28

  • 提交紀錄:Accepted ×4 → Runtime Error → Accepted

解題思路
#

視窗裡要全部變成同一個字元,最省的做法是保留出現最多的那個,替換其他 長度 - 最多次數 個。右邊每次擴張一格,如果需要替換的數量超過 k 就把左邊縮一格(Sliding Window 模板二)。字母只有 26 個,每次取 max(count.values()) 是 O(26)。

我的嘗試
#

2022 年就 AC 了,2026 年重寫時一次 RE:寫成 max(count)(拿到的是字元 key,跟整數比較 TypeError),縮左邊時也寫成 count[i](index 而不是字元),兩個都改掉才 AC。

正確解法
#

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        count = defaultdict(int)
        res = l = 0
        for r, ch in enumerate(s):
            count[ch] += 1
            while (r - l + 1) - max(count.values()) > k:
                count[s[l]] -= 1
                l += 1
            res = max(res, r - l + 1)
        return res

複雜度
#

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

要特別避免的錯誤
#

  • 縮左邊時要減的是 count[s[l]](字元),不是 count[l](index)。
  • max(count) 取的是 key 的最大值,要取次數得用 max(count.values())。

面試口說整理
#

我用可變長度的滑動視窗,視窗長度減掉最多的字元次數就是需要替換的數量,超過 k 就縮左邊,過程中記錄最長的視窗。字母只有 26 個,時間 O(26n)。

相關文章

LeetCode 981: Time Based Key-Value Store
·2 分鐘
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 解題筆記:每個 key 存一個 (timestamp, value) 的 list,timestamp 是遞增的;get 時二分找最後一個 timestamp <= 查詢時間的
LeetCode 49: Group Anagrams
·1 分鐘
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 解題筆記:把每個字串排序後當成 key,同一個 key 的字串就是同一組 anagram
LeetCode 17: Letter Combinations of a Phone Number
·1 分鐘
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 解題筆記:每一層處理一個數字,枚舉它對應的字母;空字串要回傳空 list
LeetCode 128: Longest Consecutive Sequence
·1 分鐘
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 解題筆記:放進 set,只從「x - 1 不在 set 裡」的數開始往上數,每個數最多被看兩次,O(n)
LeetCode 347: Top K Frequent Elements
·1 分鐘
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 解題筆記:先計數,再用大小為 k 的 heap 或 bucket sort(次數當 index)取出次數最多的 k 個
LeetCode 79: Word Search
·2 分鐘
LeetCode Medium Array String Backtracking Depth-First-Search
LeetCode 79 解題筆記:從每一格開始回溯,往四個方向比對下一個字元,走過的格子暫時標記,回溯時還原;先用字元次數剪枝