Repository navigation
Expand file tree
/
Copy pathdesign_a_trie.cpp
More file actions
71 lines (64 loc) · 1.83 KB
/
Copy pathdesign_a_trie.cpp
File metadata and controls
71 lines (64 loc) · 1.83 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
71
#include <unordered_map>
#include <string>
class TrieNode {
public:
std::unordered_map<char, TrieNode*> children;
bool isWord;
TrieNode() : isWord(false) {}
~TrieNode() {
for (auto& pair : children) {
delete pair.second;
}
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
~Trie() {
delete root;
}
void insert(std::string word) {
TrieNode* node = root;
for (char c : word) {
// For each character in the word, if it's not a child of
// the current node, create a new TrieNode for that
// character.
if (node->children.find(c) == node->children.end()) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
// Mark the last node as the end of a word.
node->isWord = true;
}
bool search(std::string word) {
TrieNode* node = root;
for (char c : word) {
// For each character in the word, if it's not a child of
// the current node, the word doesn't exist in the Trie.
if (node->children.find(c) == node->children.end()) {
return false;
}
node = node->children[c];
}
// Return whether the current node is marked as the end of the
// word.
return node->isWord;
}
bool hasPrefix(std::string prefix) {
TrieNode* node = root;
for (char c : prefix) {
if (node->children.find(c) == node->children.end()) {
return false;
}
node = node->children[c];
}
// Once we've traversed the nodes corresponding to each
// character in the prefix, return True.
return true;
}
private:
TrieNode* root;
};