208. Implement Trie (Prefix Tree)

problem

solution

先定義TrieNode 資料結構
Trie 只有葉子才會存資料,其餘只是指標

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
struct TrieNode{
TrieNode* child[26];
bool isWord;
TrieNode():isWord(false){
for(TrieNode* &c:child) c= nullptr;
}

};
class Trie {
private:
TrieNode * root;
public:
Trie() {
root = new TrieNode();
}

void insert(string word) {
TrieNode *cur = root;
for(char c:word){
if(!cur->child[c-'a']) cur->child[c-'a'] = new TrieNode();
cur = cur->child[c-'a'];
}
cur->isWord = true;
}

bool search(string word) {
TrieNode *cur = root;
for(char c:word){
if(!cur->child[c-'a']) return false;
cur = cur->child[c-'a'];
}
return cur->isWord;
}

bool startsWith(string prefix) {
TrieNode *cur = root;
for(char c:prefix){
if(!cur->child[c-'a']) return false;
cur = cur->child[c-'a'];
}
return true;
}
};

analysis

search、insert、startWith operation

  • time complexity O(n) , n = len(word)