trie

LC 208. Implement Trie(Prefix Tree)

Not fast… But it’s bug free at the first commitment. I’m soooo happy.

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
45
46
47
48
49
50
51
52
53
54
55
56
struct  {
bool end = false;
vector<TrieNode*> alpha;
TrieNode(){
alpha = vector<TrieNode*>(26, NULL);
}
};

class Trie {
public:
TrieNode* root;

Trie() {
root = new TrieNode();
}

/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* temp = root;
for(int i = 0; i < word.length(); i++){
int cind = word[i] - 'a';
if(!temp->alpha[cind]){
temp->alpha[cind] = new TrieNode();
}
temp = temp->alpha[cind];
}
temp->end = true;
}

/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* temp = root;
for(char c : word){
int cind = c - 'a';
if(!temp->alpha[cind])
return false;
temp = temp->alpha[cind];
}
if(!temp->end)
return false;

return true;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* temp = root;
for(char c : prefix){
int cind = c - 'a';
if(!temp->alpha[cind])
return false;
temp = temp->alpha[cind];
}
return true;
}
};