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

LeetCode 3803: Count Residue Prefixes

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

基本資料
#

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

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

解題思路
#

前綴一個字一個字變長,不同字元數用集合邊掃邊維護(String 模板四)。長度是 i + 1,比較 len(seen) == (i + 1) % 3。

我的解法
#

class Solution:
    def residuePrefixes(self, s: str) -> int:
        seen, res = set(), 0
        for i, ch in enumerate(s):
            seen.add(ch)
            res += len(seen) == (i + 1) % 3
        return res

複雜度
#

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

要特別避免的錯誤
#

  • 長度是 i + 1,不是 i。

面試口說整理
#

我由左到右掃,用集合記前綴裡出現過的字元,每一步比較集合大小和前綴長度 mod 3。時間 O(n)。因為長度 mod 3 最多是 2,不同字元數超過 2 之後就不可能再成立,可以提早結束。

相關文章

LeetCode 3090: Maximum Length Substring With Two Occurrences
·1 分鐘
LeetCode Easy Sliding-Window Hash-Table String
LeetCode 3090 解題筆記:「求最長」的滑動視窗,剛加進來的字元超過 2 次就縮左邊
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 解題筆記:分別收集出現過的小寫和大寫字母,兩個集合的交集大小就是答案
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
LeetCode 804: Unique Morse Code Words
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 804 解題筆記:把每個單字轉成摩斯碼字串,放進集合後算有幾種