LeetCode 208. Implement Trie (Prefix Tree)

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
class Trie {
private:
struct TrieNode {
TrieNode(): is_word(false), children(26, nullptr) {}
~TrieNode() {
for (TrieNode* child : children)
if (child) delete child;
}
bool is_word;
vector<TrieNode*> children;
};
const TrieNode* find(const string& prefix) const {
const TrieNode* p = root_.get();
for (const char c : prefix) {
p = p->children[c - 'a'];
if (p == nullptr) break;
}
return p;
}
public:
std::unique_ptr<TrieNode> root_;
Trie():root_(new TrieNode()) {}
void insert(string word) {
TrieNode* p = root_.get();
for (const char c : word) {
if (!p->children[c - 'a'])
p->children[c - 'a'] = new TrieNode();
p = p->children[c - 'a'];
}
p->is_word = true;
}
bool search(string word) {
const TrieNode* p = find(word);
return p && p->is_word;
}
bool startsWith(string prefix) {
return find(prefix) != nullptr;
}
};