这题就是Trie树,我们对于读入,用cin.getline()读入,如果他遇到enter就结束读入,所以字符串的长度就是0,然后我们就退出读入即可。
Trie的简单讲解:https://blog.csdn.net/qq_41090676/article/details/86775990
Trie的高质量详细讲解:https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html
#include <iostream>
#include <cstring>
using namespace std;
int trie[400010][29], sum[400010];
int len, root, tot=0;
char s[15];
void insert()
{
root=0;
len = strlen(s);
for (int i = 0; i < len;i++) {
int id = s[i] - 'a';
if (!trie[root][id])
trie[root][id] = ++tot;
sum[trie[root][id]]++;
root = trie[root][id];
}
}
int search()
{
root = 0;
len=strlen(s);
for (int i = 0; i < len;i++) {
int id = s[i] - 'a';
if (!trie[root][id])
return 0;
root = trie[root][id];
}
return sum[root];
}
int main()
{
while (cin.getline(s,12)) {
if (strlen(s)==0)
break;
insert();
}
while (scanf("%s",&s)!=EOF) {
printf("%d
", search());
}
return 0;
}