-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement Trie Prefix Tree.cpp
51 lines (45 loc) · 1.11 KB
/
Implement Trie Prefix Tree.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
#include <iostream>
class Trie {
public:
Trie *children[26] = {nullptr};
bool ok = false;
Trie() {}
~Trie() {
for (int i = 0; i < 26; ++i) {
if (children[i] != nullptr) {
delete children[i];
}
}
}
void insert(std::string word) {
Trie *cur = this;
for (char c : word) {
std::cout << c << std::endl;
if (!cur->children[c - 'a']) {
cur->children[c - 'a'] = new Trie;
}
cur = cur->children[c - 'a'];
}
cur->ok = true;
}
bool search(std::string word) {
Trie *cur = this;
for (char c : word) {
if (!cur->children[c - 'a']) {
return false;
}
cur = cur->children[c - 'a'];
}
return cur->ok;
}
bool startsWith(std::string prefix) {
Trie *cur = this;
for (char c : prefix) {
if (!cur->children[c - 'a']) {
return false;
}
cur = cur->children[c - 'a'];
}
return true;
}
};