本文完整拆解 LeetCode 1804 Implement Trie II 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Implement Trie II 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()Initializes the trie object.void insert(String word)Inserts the stringwordinto the trie.int countWordsEqualTo(String word)Returns the number of instances of the stringwordin the trie.int countWordsStartingWith(String prefix)Returns the number of strings in the trie that have the stringprefixas a prefix.void erase(String word)Erases the stringwordfrom the trie.
Example 1:
Input
["Trie", "insert", "insert", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsStartingWith"]
[[], ["apple"], ["apple"], ["apple"], ["app"], ["apple"], ["apple"], ["app"], ["apple"], ["app"]]
Output
[null, null, null, 2, 2, null, 1, 1, null, 0]
Explanation
Trie trie = new Trie();
trie.insert("apple"); // Inserts "apple".
trie.insert("apple"); // Inserts another "apple".
trie.countWordsEqualTo("apple"); // There are two instances of "apple" so return 2.
trie.countWordsStartingWith("app"); // "app" is a prefix of "apple" so return 2.
trie.erase("apple"); // Erases one "apple".
trie.countWordsEqualTo("apple"); // Now there is only one instance of "apple" so return 1.
trie.countWordsStartingWith("app"); // return 1
trie.erase("apple"); // Erases "apple". Now the trie is empty.
trie.countWordsStartingWith("app"); // return 0
Constraints:
1 <= word.length, prefix.length <= 2000wordandprefixconsist only of lowercase English letters.- At most
3 * 104calls in total will be made toinsert,countWordsEqualTo,countWordsStartingWith, anderase. - It is guaranteed that for any function call to
erase, the stringwordwill exist in the trie.
Python
class TrieNode:
def __init__(self):
self.links = [None] * 26
self.wordsEndingHere = 0
self.wordsStartingHere = 0
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for w in word:
charIndex = ord(w) - ord('a')
if not node.links[charIndex]:
node.links[charIndex] = TrieNode()
node = node.links[charIndex]
node.wordsStartingHere += 1
node.wordsEndingHere += 1
def countWordsEqualTo(self, word: str) -> int:
node = self.root
for w in word:
charIndex = ord(w) - ord('a')
if not node.links[charIndex]:
return 0
node = node.links[charIndex]
return node.wordsEndingHere
def countWordsStartingWith(self, prefix: str) -> int:
node = self.root
for w in prefix:
charIndex = ord(w) - ord('a')
if not node.links[charIndex]:
return 0
node = node.links[charIndex]
return node.wordsStartingHere
def erase(self, word: str) -> None:
node = self.root
for w in word:
charIndex = ord(w) - ord('a')
node = node.links[charIndex]
node.wordsStartingHere -= 1
node.wordsEndingHere -= 1
# Your Trie object will be instantiated and called as such:
trie = Trie()
trie.insert("apple")
trie.insert("apple")
print(trie.countWordsEqualTo("apple"))
print(trie.countWordsStartingWith("app"))
trie.erase("apple")
print(trie.countWordsEqualTo("apple"))
print(trie.countWordsStartingWith("app"))
trie.erase("apple")
print(trie.countWordsStartingWith("app"))
Implement Trie II 解題思路
相較於基本版,這一版要支援「同一個單字插入多次」與「刪除」,所以旗標不夠用,必須改成計數器:每個節點記錄 countPrefix(有多少單字經過這裡)與 countWord(有多少單字在這裡結束)。刪除時沿路把計數減一即可,不必真的回收節點。
Implement Trie II 演算法步驟
- 節點改存兩個整數:countPrefix 與 countWord。
- insert:沿路每個節點 countPrefix++,終點節點 countWord++。
- countWordsEqualTo:走到終點回傳 countWord,中途斷掉回傳 0。
- erase:沿路每個節點 countPrefix–,終點 countWord–;countWordsStartingWith 則回傳終點的 countPrefix。
Implement Trie II 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(L) |
| 空間複雜度 | O(N·L) |
四個操作都只沿單一路徑走 L 步,時間皆為 O(L)。空間與基本版相同為 O(N·L),只是每個節點多存兩個整數。用計數取代旗標,讓刪除變成 O(L) 的減法而非昂貴的節點回收。
Implement Trie II 的邊界情況與常見錯誤
- 題目保證 erase 只會對存在的單字呼叫,否則計數會變成負數。
- countPrefix 與 countWord 不能共用同一個欄位,前綴數一定大於等於單字數。
- 重複插入同一個單字時 countWord 要累加而不是設為 1。
- 即使計數歸零也可以保留節點,實作最簡單且不影響正確性。
Implement Trie II 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 雜湊表記錄單字出現次數 | O(1) 查詢 / O(N) 前綴 | O(N·L) | 前綴統計要掃全表 |
| 基本 Trie + 外部計數表 | O(L) | O(N·L) | 兩份資料要同步,容易出錯 |
| 節點內建雙計數器 | O(L) | O(N·L) | 本文採用 |
