-
Notifications
You must be signed in to change notification settings - Fork 77
/
Trie.cpp
52 lines (50 loc) · 1.31 KB
/
Trie.cpp
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
const static int SIZE = 30;
const static int NOT_FOUND = -1;
class trie {
private:
struct trieNode {
int mark;
trieNode* children[SIZE];
trieNode(): mark(NOT_FOUND) {
for (int i = 0; i < SIZE; ++i) {
children[i] = nullptr;
}
}
~trieNode() {
for (int i = 0; i < SIZE; ++i) {
delete children[i];
children[i] = nullptr;
}
}
};
trieNode* root;
public:
trie(): root(new trieNode()) {
}
~trie() {
delete root;
root = nullptr;
}
void insert(string const& key, int id) {
trieNode* pCrawl = root;
for (int i = 0; i < (int)key.length(); ++i) {
int indx = key[i] - 'a';
if (!pCrawl->children[indx]) {
pCrawl->children[indx] = new trieNode();
}
pCrawl = pCrawl->children[indx];
}
pCrawl->mark = id;
}
int search(string const& key) {
trieNode *pCrawl = root;
for (int i = 0; i < (int)key.length(); ++i) {
int indx = key[i] - 'a';
if (!pCrawl->children[indx]) {
return NOT_FOUND;
}
pCrawl = pCrawl->children[indx];
}
return pCrawl->mark;
}
};