-
Notifications
You must be signed in to change notification settings - Fork 0
/
TRIE.cpp
63 lines (50 loc) · 1.18 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
63
struct node {
bool endmark;
node *next[26+1];
node() {
endmark = false;
for(int i = 0; i<26; i++) next[i] = NULL;
}
};
struct TRIE {
node *root;
bool pre;
TRIE() {
root = new node();
pre = false;
}
void insert(string str) {
node *curr = root;
int cnt = 0;
int len = str.size();
for(int i=0; i<len; i++) {
int id = str[i] - 'a';
if(curr->next[id]==NULL) {
curr->next[id] = new node();
} else cnt++;
if(curr->endmark) pre = true;
curr = curr->next[id];
}
if(cnt==len) pre = true;
curr->endmark = true;
}
bool search(string str) {
node *curr = root;
int len = str.size();
for(int i=0; i<len; i++) {
int id = str[i] - 'a';
if(curr->next[id]==NULL) return false;
curr = curr->next[id];
}
return curr->endmark;
}
void del(node *curr) {
for(int i=0; i<26; i++) {
if(curr->next[i]) del(curr->next[i]);
}
delete(curr);
}
bool prefix() {
return pre;
}
};