-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtrie.cpp
More file actions
36 lines (32 loc) · 722 Bytes
/
trie.cpp
File metadata and controls
36 lines (32 loc) · 722 Bytes
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
#include "trie.h"
#include <cassert>
Trie::Trie() {
std::fill(nodes, nodes + NUM_LETTERS, nullptr);
}
Trie::~Trie() {
Iter i = iter();
while (i.next()) { delete i.get(); }
}
void Trie::add(const std::string& str) {
Trie* ptr = this;
for (char c : str) {
const int ix = c - 'A';
assert(ix >= 0 && ix < NUM_LETTERS);
if (ptr->nodes[ix] == nullptr) {
ptr->nodes[ix] = new Trie();
}
ptr = ptr->nodes[ix];
}
}
bool Trie::has(const std::string& str) const {
const Trie* ptr = this;
for (char c : str) {
const int ix = c - 'A';
assert(ix >= 0 && ix < NUM_LETTERS);
if (ptr->nodes[ix] == nullptr) {
return false;
} else {
ptr = ptr->nodes[ix];
}
}
}