forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie(Pointer).cpp
78 lines (71 loc) · 933 Bytes
/
Trie(Pointer).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
78
#include <cstdio>
#include <cstring>
#define NIL 0
using namespace std;
struct node
{
int info;
node *next[26];
};
node root;
void insert(char *s)
{
int l = strlen(s);
node *cur = &root;
for (int i = 0; i < l; i++)
{
if (cur->next[s[i] - 'a'] == NIL)
{
node *o = new node;
o->info = 0;
cur->next[s[i] - 'a'] = o;
}
cur = cur->next[s[i] - 'a'];
}
cur->info++;
}
int find(char *s)
{
int l = strlen(s);
node *cur = &root;
for (int i = 0; i < l; i++)
{
if (cur->next[s[i] - 'a'] == NIL)
{
return -1;
}
else
{
cur = cur->next[s[i] - 'a'];
}
}
return cur->info;
}
int main()
{
int in;
char str[100];
while (true)
{
scanf("%d", &in);
if (in == 1)
{
scanf("%s", str);
insert(str);
}
else if (in == 2)
{
scanf("%s", str);
printf("%d\n", find(str));
}
else if (in == 0)
{
return 0;
}
else
{
printf("No such command!\n");
}
}
return 0;
}