-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_Trie.cpp
More file actions
70 lines (61 loc) · 1.8 KB
/
Copy pathImplement_Trie.cpp
File metadata and controls
70 lines (61 loc) · 1.8 KB
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
#include <vector>
#include <string>
struct TrieNode {
std::vector<TrieNode*> children; // Store all the children along with their
// corresponding node pointers
bool endOfWord = false;
TrieNode() : children(26, nullptr), endOfWord(false) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(std::string word) {
TrieNode* curr = root;
for (int i=0; i<word.size(); i++) {
if (curr->children[word[i] - 'a'] == nullptr) {
// create new node if not a child
TrieNode* temp = new TrieNode();
curr->children[word[i]-'a'] = temp;
}
curr = curr->children[word[i]-'a'];
// Set end of word
if (i == word.size()-1) {
curr->endOfWord = true;
}
}
}
bool search(std::string word) {
TrieNode* curr = root;
for (int i=0; i<word.size(); i++) {
if (curr->children[word[i]-'a'] == nullptr) {
return false;
}
curr = curr->children[word[i]-'a'];
if (i == word.size() - 1) {
return curr->endOfWord;
}
}
return false;
}
bool startsWith(std::string prefix) {
TrieNode* curr = root;
for (int i=0; i<prefix.size(); i++) {
if (curr->children[prefix[i]-'a'] == nullptr) {
return false;
}
curr = curr->children[prefix[i]-'a'];
}
return true;
}
};
/**
* 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);
*/