Skip to content

Commit b938d16

Browse files
committed
Create implement-trie-prefix-tree.cpp
1 parent 1132861 commit b938d16

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

C++/implement-trie-prefix-tree.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// Time: O(n), per operation
2+
// Space: O(1)
3+
4+
class TrieNode {
5+
public:
6+
// Initialize your data structure here.
7+
TrieNode() : is_string(false) {
8+
9+
}
10+
bool is_string;
11+
unordered_map<char, TrieNode *> leaves;
12+
};
13+
14+
class Trie {
15+
public:
16+
Trie() {
17+
root_ = new TrieNode();
18+
}
19+
20+
// Inserts a word into the trie.
21+
void insert(string word) {
22+
auto *cur = root_;
23+
for (const auto& c : word) {
24+
if (!cur->leaves.count(c)) {
25+
cur->leaves[c] = new TrieNode();
26+
}
27+
cur = cur->leaves[c];
28+
}
29+
cur->is_string = true;
30+
}
31+
32+
// Returns if the word is in the trie.
33+
bool search(string word) {
34+
auto *node = childSearch(word);
35+
if (node) {
36+
return node->is_string;
37+
}
38+
return false;
39+
}
40+
41+
// Returns if there is any word in the trie
42+
// that starts with the given prefix.
43+
bool startsWith(string prefix) {
44+
return childSearch(prefix);
45+
}
46+
47+
TrieNode * childSearch(const string& word) {
48+
auto *cur = root_;
49+
for (const auto& c : word) {
50+
if (cur->leaves.count(c)) {
51+
cur = cur->leaves[c];
52+
} else {
53+
return nullptr;
54+
}
55+
}
56+
return cur;
57+
}
58+
59+
private:
60+
TrieNode* root_;
61+
};
62+
63+
// Your Trie object will be instantiated and called as such:
64+
// Trie trie;
65+
// trie.insert("somestring");
66+
// trie.search("key");

0 commit comments

Comments
 (0)