Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
思路
这道题做法至少应该是两种,可以用字典树也可以选择用map。
- 字典树的的做法就是统计根节点因为插入的时候字符串是逐个遍历的,刚好可以满足前缀的统计。查询的时候直接按顺序遍历完这个字符串,如果中途出现发现有前缀字符串没出现过说明为0。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 1000005;
int trie[maxn][27];
int num[maxn];
int pos;
void insert(char *s)
{
int n = strlen(s);
int root = 0;
for(int i = 0;i < n;i++){
int k = s[i] - 'a';
if(trie[root][k] == 0){
trie[root][k] = ++pos;
}
root = trie[root][k];
num[root]++;
}
}
int find_s(char *s)
{
int n = strlen(s);
int root = 0;
for(int i = 0;i < n;i++){
int k = s[i] - 'a';
if(!trie[root][k]){
return 0;
}
root = trie[root][k];
}
return num[root];
}
int main()
{
char str[15];
pos = 0;
memset(num,0,sizeof(num));
memset(trie,0,sizeof(trie));
while(gets(str)){
if(str[0] == '\0') break;
insert(str);
}
while(gets(str)){
int ans = find_s(str);
printf("%d\n",ans);
}
return 0;
}
- map的做法就是倒过来从’\0’的位置遍历字符串,每次把最后一个字符置为’\0’然后加入容器。查询直接输出即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
int main()
{
char str[15];
map<string,int>m;m.clear();
while(gets(str)){
if(str[0] == '\0') break;
int n = strlen(str);
for(int i = n;i >= 0;i--){
str[i] = '\0';
m[str]++;
}
}
while(gets(str)){
printf("%d\n",m[str]);
}
return 0;
}
愿你走出半生,归来仍是少年~