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

LeetCode 3839: Number of Prefix Connected Groups

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

基本資料
#

難易度: medium 第一次嘗試:2026-02-14

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

「前 k 個字元相同」是等價關係,所以同一個前綴的字自成一組,不用 Union-Find。用 word[:k] 當 key 計數,至少兩個字的 key 就是一組(Hash Table 模板一)。

我的嘗試
#

第一版沒有排除長度不到 k 的字:Python 的 word[:k] 不會報錯,只會回傳整個字。例如 ["b", "b"]、k = 2:兩個字都太短,答案是 0,這版把兩個 "b" 算成一組,回傳 1。加上 len(g) == k 就 AC 了。

正確解法
#

class Solution:
    def prefixConnected(self, words: List[str], k: int) -> int:
        cnt = Counter(w[:k] for w in words if len(w) >= k)
        return sum(v >= 2 for v in cnt.values())

複雜度
#

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

要特別避免的錯誤
#

  • 切片超過長度不會報錯,太短的字要自己排除。

面試口說整理
#

前 k 個字元相同就連通,而且這是等價關係,所以每個前綴就是一組。我用 word[:k] 計數,排除太短的字,最後數有幾個前綴至少出現兩次。時間 O(nk)。

相關文章

LeetCode 2131: Longest Palindrome by Concatenating Two Letter Words
·1 分鐘
LeetCode Medium Greedy Hash-Table String Counting
LeetCode 2131 解題筆記:每個字跟它的反轉配成一對放兩邊;本身是回文的字也能兩兩配對,只有剩下的一個能放正中間
LeetCode 3805: Count Caesar Cipher Pairs
·1 分鐘
LeetCode Medium Math Hash-Table String Counting
LeetCode 3805 解題筆記:把每個字串整串平移到第一個字母是 a,凱薩等價的字串會變成一樣;再數每種正規化結果的配對數
LeetCode 244: Shortest Word Distance II
·1 分鐘
LeetCode Medium Two-Pointers Design Hash-Table String Array
LeetCode 244 解題筆記:預處理每個字的出現位置(天然排序),查詢時對兩個位置列表做雙指針合併,每次移動比較小的那個
LeetCode 923: 3Sum With Multiplicity
·3 分鐘
LeetCode Medium Two-Pointers Sorting Hash-Table Counting Array
LeetCode 923 解題筆記:排序後固定第一個數、對撞指針找另外兩個;兩端值相同時用組合數一次算完,不同時把兩端各自的重複數相乘
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