-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie_code.cpp
56 lines (48 loc) · 1.17 KB
/
trie_code.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
# include <vector>
# include <string>
using namespace std;
class TrieNode {
public:
vector<TrieNode*> child;
bool isEndOfWord;
TrieNode() {
child.assign(26, NULL);
isEndOfWord = false;
}
};
class Trie {
private:
TrieNode* root;
public:
Trie(const vector<string> &words) {
root = new TrieNode();
for (int i = 0; i < words.size(); i++) {
insertWord(words[i]);
}
}
TrieNode* getRoot() {
return root;
}
void insertWord(const string &word) {
TrieNode* currNode = root;
for (int i = 0; i < word.size(); i++) {
int indx = word[i] - 'a';
if (currNode->child[indx] == NULL) {
currNode->child[indx] = new TrieNode();
}
currNode = currNode->child[indx];
}
currNode->isEndOfWord = true;
}
bool search(TrieNode *root, string &word) {
TrieNode *currNode = root;
for (int i = 0; i < word.size(); i++) {
int indx = word[i] - 'a';
if (currNode->child[indx] == NULL) {
return false;
}
currNode = currNode->child[indx];
}
return (currNode != NULL && currNode->isEndOfWord);
}
};