-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefixTrie2.cpp
56 lines (48 loc) · 1.21 KB
/
prefixTrie2.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
class Trie {
public:
Trie* childrens[26] = {};
bool isWord;
vector<string> words;
Trie* root = this;
Trie() {
this->isWord = false;
}
Trie(vector<string>& words) {
this->words = words;
this->isWord = false;
this->populateTrieNodes(words);
}
void populateTrieNodes(vector<string>& words) {
for(string& w : words) {
Trie* curr = this;
for(char& c : w) {
this->insertNode(curr, c);
}
curr->isWord = true;
}
}
void insertNode(Trie* &curr, char c) {
if(curr->childrens[c - 'a'] == nullptr) {
curr->childrens[c - 'a'] = new Trie();
}
curr = curr->childrens[c - 'a'];
}
bool contains(string word) {
Trie* curr = this;
for(char& c : word) {
if(curr->childrens[c - 'a'] == nullptr) {
return false;
}
curr = curr->childrens[c - 'a'];
}
return curr->isWord;
}
};
int main() {
vector<string> words = {"oath", "oat", "apple", "appie"};
Trie *t = new Trie(words);
if(t->contains("oath")) {
cout << "contains" << endl;
}
return 0;
}