-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.h
117 lines (90 loc) · 2.16 KB
/
Trie.h
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#ifndef _TRIE_H
#define _TRIE_H
#include <map>
#include <string>
#include <iostream>
#include <vector>
template <class T>
class TrieNode
{
public:
TrieNode(const T& object) : terminal_(false), object_(object) {}
TrieNode() : terminal_(false), object_() {}
inline bool isTerminal() { return terminal_; }
void setTerminal(bool orly) { terminal_ = orly; }
const T* getObject() { return &object_; }
void setObject(const T& object) { object_ = object; }
bool hasChild(char value) const
{
return (childNodes_.find(value) != childNodes_.end());
}
TrieNode* addChild(char value, const T& object)
{
if (!hasChild(value)) {
childNodes_[value] = TrieNode();
} else
object_ = object;
return getChild(value);
}
TrieNode* getChild(char value)
{
return &childNodes_[value];
}
std::map<char, TrieNode>* getChildNodes()
{
return &childNodes_;
}
private:
bool terminal_;
std::map<char, TrieNode> childNodes_;
T object_;
};
template <class T>
class Trie
{
public:
Trie() : root_(new TrieNode<T>()) {}
TrieNode<T> *insert(const std::string&, const T&);
TrieNode<T> *find(const std::string&) const;
private:
TrieNode<T>* root_;
};
template <class T> TrieNode<T>* Trie<T>::insert(
const std::string& str,
const T& object
)
{
TrieNode<T>* current = root_;
std::string::const_iterator iter = str.begin();
while (iter != str.end()) {
current = current->addChild(*iter, object);
++iter;
}
current->setTerminal(true);
current->setObject(object);
return current;
};
template <class T> TrieNode<T>* Trie<T>::find(
const std::string& str
) const
{
TrieNode<T>* current = root_;
std::vector<TrieNode<T>*> foundNodes;
bool found = false;
std::string::const_iterator iter = str.begin();
while (iter != str.end()) {
if (!current->hasChild(*iter))
break;
current = current->getChild(*iter);
if (current->isTerminal()) {
foundNodes.push_back(current);
found = true;
}
++iter;
}
if (found)
return foundNodes.back();
else
return 0;
}
#endif /* _TRIE_H */