208. Implement Trie (Prefix Tree)
題目網址:https://leetcode.cn/problems/implement-trie-prefix-tree/
題意:Trie 也稱作 prefix tree, 是一種可以高效儲存、取得 string 中的 key 的資料結構。這一資料結構有相當多的應用情境, 例如 : 自動補全和拼寫檢查。
請實現
Trie
class:
Trie()
:初始化 trie objectvoid insert(String word)
:插入word
bool search(String word)
:返回word
是否已經存在於 trie 中boolean startsWith(String prefix)
:若已經插入的word
的前綴之一為prefix
, 則 returntrue
注意:
word
和prefix
僅由小寫字母所組成。
Solution:
想法:先用一個
root
作為所有開頭 TrieNode 之 dummy node
Trie()
: 初始化root
void insert(String word)
: 遍歷 word 中的每個 char, 若p->children[ch - 'a']
為null
, 則新增一 TrieNode 並指向它, 當走到 word 之 end, 記得將 trie 中的 end node 之isEnd
設為true
bool search(String word)
和boolean startsWith(String prefix)
: 兩者皆得遍歷傳入參數的每個 char, 因此我額外寫了一個TrieNode* find(string& word)
來遍歷
TrieNode* find(string& word)
: 若 word 不在 trie 中, 則返回 nullptr。否則, 返回 end node 之 ptrbool search(String word)
: 若 end node 之 ptrp
存在, 且p->isEnd
為true
➔ 代表word
存在 trie 中, 因此返回true
boolean startsWith(String prefix)
: 若 end node 之 ptrp
存在
➔ 代表prefix
存在 trie 中, 因此返回true
e.g. 下圖為插入
["app", "ape", "at", "atp", "to"]
後的 trie, 每個 TrieNode 中的是 char 和 is_end
class TrieNode { |
- time:
- $O(1)$ ➔ 初始化 Trie
- $O(n)$ ➔ insert、search 和 startWith,
n
為要查詢或插入的 string 長度
- space:$O(26 \cdot \displaystyle\sum_{i=1}^{n}w_i)$ ➔ worse case:每個
word
的prefix
皆不重覆- $\displaystyle\sum_{i=1}^{n}w_i$:所有要插入的 string 長度之和(最大 node 數)
- $O(26)$ : 每個 node 有 26 個 children
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論