输入样例:
5
I abc
Q abc
Q ab
I ab
Q ab
输出样例:
1
0
1
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e4+10;
int son[N][26],cnt[N],idx;
char str[N];
void Insert(char c[])
{
int level = 0;
for (int i = 0; c[i]; i ++ )//到'\0'停止
{
int u = c[i]-'a';
if(!son[level][u]) son[level][u] = ++idx;//注意son[N][26]中,每层只存一个
level = son[level][u];//模拟树的向下递归
}
cnt[level]++;//全部插入,叶节点增加,表示以当前前缀结尾的字符串数量
}
int Query(char c[])//与Insert()同理
{
int level = 0;
for (int i = 0; c[i]; i ++ )
{
int u = c[i]-'a';
if(!son[level][u]) return 0;
level = son[level][u];
}
return cnt[level];
}
int main()
{
int n;
char op;
cin >> n;
while (n -- )
{
scanf(" %c%s", &op, str);
if(op == 'I'){
Insert(str);
}else if(op == 'Q'){
cout << Query(str) << endl;
}
}
return 0;
}