AcWing 835. Trie字符串统计
1、题目(来源于AcWing):
维护一个字符串集合,支持两种操作:
“I x”向集合中插入一个字符串x;
“Q x”询问一个字符串在集合中出现了多少次。
共有N个操作,输入的字符串总长度不超过 105,字符串仅包含小写英文字母。
输入格式
第一行包含整数N,表示操作数。
接下来N行,每行包含一个操作指令,指令为”I x”或”Q x”中的一种。
输出格式
对于每个询问指令”Q x”,都要输出一个整数作为结果,表示x在集合中出现的次数。
每个结果占一行。
数据范围
1≤N≤2∗10^4
输入样例:
5
I abc
Q abc
Q ab
I ab
Q ab
输出样例:
1
0
1
2、基本思想:
3、C++代码如下(该代码引用AcWing网站的代码):
#include <iostream>
using namespace std;
void insert(char str[]);
int query(char str[]);
const int N = 1e5 + 10;
int n;
int son[N][26], count[N], idx;//count表示每个字符串出现的次数,idx记录树中节点的个数
char str[N];//str表示要插入或者要查找的字符串
int main()
{
cin >> n;
char op;//如果后面要用scanf输入这里就要定义成op[2],因为scanf不能自动过滤空格
while (n -- )
{
cin >> op >> str;
if (op == 'I') insert(str);
else cout << query(str) << endl;
}
return 0;
}
void insert(char str[])//插入
{
int p = 0;
for (int i = 0; str[i]; i ++ )
{
int u = str[i] - 'a';//将a~b映射成0~25
if (!son[p][u]) son[p][u] = ++ idx;//如果没有这个节点就加1
p = son[p][u];
}
count[p] ++ ;
}
int query(char str[])//查找
{
int p = 0;
for (int i = 0; str[i]; i ++ )
{
int u = str[i] - 'a';
if (!son[p][u]) return 0;
p = son[p][u];
}
return count[p];
}//该代码引用AcWing网站的代码