AcWing 835. Trie字符串统计(C++结构体写法)
原题链接
简单
作者:
虹之间
,
2020-10-21 10:01:13
,
所有人可见
,
阅读 361
#include <iostream>
#include <map>
using namespace std;
struct Node
{
char c;
int cnt; // 以该节点为结尾的单词数目
map<char, Node *> child;
Node(char c)
{
this->c = c;
this->cnt = 0;
child.clear();
}
};
Node *root;
void insert(string &word)
{
Node *p = root;
for(char c: word)
{
if(p->child.count(c) == 0)
{
Node *t = new Node(c);
p->child[c] = t;
}
p = p->child[c];
}
p->cnt ++ ;
}
int query(string &word)
{
Node *p =root;
for(char c: word)
{
if(p->child.count(c) == 0) return 0;
p = p->child[c];
}
return p->cnt;
}
int main()
{
root = new Node('#'); // 初始化根节点
int n; cin >> n;
while(n -- )
{
char op; cin >> op;
string s; cin >> s;
if(op == 'I') insert(s);
else cout << query(s) << endl;
}
}
用map会不会太慢了?