-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path208.cpp
More file actions
39 lines (34 loc) · 896 Bytes
/
Copy path208.cpp
File metadata and controls
39 lines (34 loc) · 896 Bytes
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
class Trie {
struct TrieNode {
vector<TrieNode *> next;
bool is_end;
TrieNode() : next(vector<TrieNode *>(26, nullptr)), is_end(false) {}
};
TrieNode *root;
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
auto node = root;
for (auto c:word) {
if (!node->next[c - 'a'])
node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->is_end = true;
}
bool search(string word, bool search = true) {
auto node = root;
for (auto p:word) {
if (node->next[p - 'a'])
node = node->next[p - 'a'];
else
return false;
}
return search ? node->is_end : true;
}
bool startsWith(string prefix) {
return search(prefix, false);
}
};