-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrie.hpp
98 lines (82 loc) · 2.76 KB
/
trie.hpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <string_view>
#include <unordered_map>
#include <vector>
#include <memory>
namespace trie {
// TODO: add feature allowing allocating elements using different
// policies. Add some general predefined policies. Also make it possible
// to write custom policy according to application logic. Also write
// analyzer which will try to produce optimal policy.
class Trie {
public:
struct TrieNode {
std::unordered_map<char, std::unique_ptr<TrieNode>> childs;
bool is_final = false;
};
Trie(): root_(std::make_unique<TrieNode>()) {}
void insert(std::string_view s) {
// TODO: can we avoid calling get() and work with unique_ptr directly?
TrieNode *node = root_.get();
for (const auto& symbol : s) {
if (node->childs.count(symbol) == 0) {
node->childs[symbol] = std::make_unique<TrieNode>();
++size_;
}
node = node->childs[symbol].get();
}
node->is_final = true;
}
size_t size() const {
return size_;
}
bool contains(std::string_view s) {
TrieNode *node = root_.get();
for (const auto& symbol: s) {
if (node->childs.count(symbol) == 0) {
return false;
}
node = node->childs[symbol].get();
}
return node->is_final;
}
bool check_concat(std::string_view s) {
TrieNode *node = root_.get();
bool last_node_was_final = false;
for (const auto& symbol: s) {
if (node->childs.count(symbol) == 0) {
if (!last_node_was_final) {
return false;
}
node = root_.get();
if (node->childs.count(symbol) == 0) {
return false;
}
}
node = node->childs[symbol].get();
last_node_was_final = node->is_final;
}
return last_node_was_final;
}
friend std::ostream &operator<<(std::ostream &os, const Trie &t);
private:
std::unique_ptr<TrieNode> root_;
size_t size_ = 1;
};
std::ostream &operator<<(std::ostream &os, const Trie::TrieNode &n);
std::ostream &operator<<(std::ostream &os, const std::unordered_map<char, std::unique_ptr<Trie::TrieNode>> &m) {
os << "{";
for (const auto& elem: m) {
os << "{" << elem.first << ": " << *(elem.second.get()) << "}, ";
}
os << "}";
return os;
}
std::ostream &operator<<(std::ostream &os, const Trie::TrieNode &n) {
os << "<TrieNode: is_final=" << n.is_final << ", elems=\n" << n.childs << ">";
return os;
}
std::ostream &operator<<(std::ostream &os, const Trie &t) {
os << "<Trie: size=" << t.size() << ", elems=\n" << *(t.root_.get());
return os;
}
}; // namespace trie