-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
78 lines (77 loc) · 1.67 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Node{
public:
Node *children[26];
public:
int cnt = 0;
public:
char t;
public:
Node(int alphabet, char c)
{
REP(i,0,alphabet)
this->children[i] = NULL;
t = c;
}
};
class Trie{
Node *root;
int alphabet;
char start;
public:
Trie(int alphabet, char start)
{
this->alphabet = alphabet;
root = new Node(alphabet,'*');
this->start = start;
}
public:
void insert(string str)
{
Node *cur = root;
REP(i,0,str.L)
{
if (cur->children[str[i]-start] == NULL)
{
cur->children[str[i]-start] = new Node(alphabet,str[i]);
}
cur = cur->children[str[i]-start];
}
cur->cnt++;
}
public:
bool exists(string str)
{
Node *cur = root;
REP(i,0,str.L)
{
if (cur->children[str[i]-start] == NULL)
return false;
cur = cur->children[str[i]-start];
}
return (cur->cnt > 0);
}
public:
int count(string str)
{
Node *cur = root;
REP(i,0,str.L)
{
if (cur->children[str[i]-start] == NULL)
return 0;
cur = cur->children[str[i]-start];
}
return (cur->cnt);
}
public:
void erase(string str)
{
Node *cur = root;
REP(i,0,str.L)
{
if (cur->children[str[i]-start] == NULL)
cur->children[str[i]-start] = new Node(alphabet,str[i]);
cur = cur->children[str[i]-start];
}
cur->cnt--;
}
};