本题用字典树即可,在每个节点上设置一个计数变量cnt,用于统计从根节点到本节点的前缀的数量。
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
typedef struct Node
{
int cnt;
Node *child[26];
Node()
{
cnt = 1;
memset(child, 0, sizeof(child));
}
};
Node *root = new Node;
void Insert(string str)
{
int len = str.length();
Node *p = root;
for(int i = 0; i < len; i++)
{
int id = str[i] - 'a';
if(p->child[id] == 0)
p->child[id] = new Node;
else
p->child[id]->cnt++;
p = p->child[id];
}
}
void Search(string str)
{
int len = str.length();
Node *p = root;
for(int i = 0; i < len; i++)
{
int id = str[i] - 'a';
if(p->child[id] != 0)
p = p->child[id];
else
{
cout << 0 << endl;
return;
}
}
cout << p->cnt << endl;
}
int main()
{
string str;
//getline()会把回车符也读入进str中,而且长度为0
while(getline(cin, str) && str.length() != 0)
Insert(str);
while(cin>> str)
Search(str);
return 0;
}