-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTrie.cpp
43 lines (40 loc) · 1.04 KB
/
Trie.cpp
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
struct Trienode {
unordered_map < int, Trienode * > child;
bool wordend = false;
};
class Trie {
public:
Trienode * root;
Trie() {
root = new Trienode();
}
void insert(string word) {
Trienode * curr = root;
for (char a: word) {
int idx = a - 'a';
if (curr -> child.count(idx) == 0) {
curr -> child[idx] = new Trienode();
}
curr = curr -> child[idx];
}
curr -> wordend = true;
}
bool search(string word) {
Trienode * curr = root;
for (char a: word) {
int idx = a - 'a';
if (curr -> child.count(idx) == 0) return false;
curr = curr -> child[idx];
}
return curr -> wordend;
}
bool startsWith(string prefix) {
Trienode * curr = root;
for (char a: prefix) {
int idx = a - 'a';
if (curr -> child.count(idx) == 0) return false;
curr = curr -> child[idx];
}
return true;
}
};