Skip to content

Commit 51540fe

Browse files
authored
Trie树(以小写字母字符串为例)
1 parent e3e52f1 commit 51540fe

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Trie.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include <cstdio>
2+
#include <cstring>
3+
4+
#define TRIE_SIZE 100000
5+
6+
using namespace std;
7+
8+
struct node
9+
{
10+
int cnt;
11+
int next[26];
12+
}T[TRIE_SIZE];
13+
14+
int nc = 2;
15+
16+
void insert(char *s)
17+
{
18+
int len = strlen(s), cur = 1;
19+
for (int i = 0; i < len; i++)
20+
{
21+
if (T[cur].next[s[i]] == 0)
22+
{
23+
T[cur].next[s[i]] = nc;
24+
cur = nc;
25+
nc++;
26+
}
27+
else
28+
{
29+
cur = T[cur].next[s[i]];
30+
}
31+
}
32+
T[cur].cnt++;
33+
}
34+
35+
int query(char *s)
36+
{
37+
int len = strlen(s), cur = 1;
38+
for (int i = 0; i < len; i++)
39+
{
40+
if (T[cur].next[s[i]] == 0)
41+
{
42+
return 0;
43+
}
44+
else
45+
{
46+
cur = T[cur].next[s[i]];
47+
}
48+
}
49+
return T[cur].cnt;
50+
}
51+
52+
int main()
53+
{
54+
int o;
55+
char s[100];
56+
while (true)
57+
{
58+
scanf("%d%s", &o, s);
59+
if (o == 1)
60+
{
61+
insert(s);
62+
}
63+
else if (o == 2)
64+
{
65+
printf("%d\n", query(s));
66+
}
67+
else
68+
{
69+
printf("No such command!\n");
70+
}
71+
}
72+
return 0;
73+
}

0 commit comments

Comments
 (0)