-
Notifications
You must be signed in to change notification settings - Fork 7
/
Trie.cpp
82 lines (75 loc) · 2 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
#include<vector>
struct Node {
Node() {
children.resize(26, nullptr);
}
vector<Node*> children;
bool wordEnds = false;
};
class Trie {
public:
Trie() {
root = new Node();
}
void insert(string word) {
if (word.size() == 0) return;
int index = 0;
Node* curr = root;
while (true) {
const char ch = word.at(index);
Node* child = curr->children.at(ch - 'a');
if (child == nullptr) {
child = new Node();
curr->children[ch - 'a'] = child;
}
curr = child;
++index;
if (index == word.size()) {
child->wordEnds = true;
break;
}
}
}
bool search(string word) {
if (word.size() == 0) return true;
int index = 0;
Node* curr = root;
while (true) {
const char ch = word.at(index);
Node* child = curr->children.at(ch - 'a');
if (child == nullptr) return false;
curr = child;
++index;
if (index == word.size()) {
return child->wordEnds;
}
}
return true;
}
bool startsWith(string prefix) {
const string& word = prefix;
if (word.size() == 0) return true;
int index = 0;
Node* curr = root;
while (true) {
const char ch = word.at(index);
Node* child = curr->children.at(ch - 'a');
if (child == nullptr) return false;
curr = child;
++index;
if (index == word.size()) {
return true;
}
}
return true;
}
private:
Node* root;
};