-
Notifications
You must be signed in to change notification settings - Fork 21
/
Trie.cpp
62 lines (49 loc) · 1.03 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
53
54
55
56
57
58
59
60
61
62
// Trie
// Insert, Query - O(logn)
// query and insert function needs to be changed according to need
#define CHILD_SIZE 26
int cnt[2][26];
struct node {
node * child[CHILD_SIZE];
int cnt;
node() {
cnt = 0;
for(int i = 0; i < CHILD_SIZE; ++i)
child[i] = NULL;
}
void clear() {
cnt = 0;
for(int i = 0; i < CHILD_SIZE; ++i) {
child[i] = NULL;
}
}
};
struct Trie {
private:
void insert(node * cur, string s) {
cur->cnt++;
for(int i = 0; i < sz(s); ++i) {
int curPos = s[i] - 'a';
if(cur->child[curPos] == NULL) {
cur->child[curPos] = new node();
++cntNodes;
}
cur = cur->child[curPos];
cur->cnt++;
}
}
public:
int cntNodes;
node * root;
Trie() {
cntNodes = 0;
root = new node();
}
~Trie() {
delete root;
}
void clear() {
cntNodes = 0;
root = new node();
}
};