-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhihoCoder-trie.cpp
More file actions
83 lines (70 loc) · 1.41 KB
/
Copy pathhihoCoder-trie.cpp
File metadata and controls
83 lines (70 loc) · 1.41 KB
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
79
80
81
82
83
#include <iostream>
using namespace std;
const int kind = 26;
struct Treenode{
int count;
Treenode* next[kind];
Treenode(){
count=1;
for(int i=0; i<kind; i++)
next[i] = NULL;
}
};
void insert(Treenode *&root, char* str){
Treenode *p = root;
int i=0;
int branch = 0;
if(root == NULL){
p=new Treenode();
root = p;
}
while(str[i]!='\0'){
branch = str[i] - 'a';
if(p->next[branch]==NULL)
p->next[branch] = new Treenode();
else
p->next[branch]->count++;
p = p->next[branch];
i++;
}
}
int search(Treenode *root, char *str){
Treenode *p = root;
int ans=0;
int i=0, branch = 0;
if (root == NULL || str == NULL)
return 0;
while(str[i]!='\0'){
branch = str[i] - 'a';
if(p->next[branch]!=NULL){
p = p->next[branch];
ans = p->count;
i++;
} else {
ans = 0;
break;
}
}
return ans;
}
int main(){
char word[101];
char ask[101];
Treenode *root = NULL;
int m, n;
// printf("n:");
scanf("%d",&n);
while(n>0){
scanf("%s", word);
insert(root, word);
n--;
}
// printf("m:");
scanf("%d",&m);
while(m>0){
scanf("%s", ask);
printf("%d\n",search(root, ask));
m--;
}
return 0;
}