0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-23 21:08:47 +00:00

835. Trie字符串统计

https://www.acwing.com/problem/content/submission/code_detail/7680320/
This commit is contained in:
Baoshuo Ren 2021-09-12 14:06:27 +08:00 committed by Baoshuo Ren
parent 9028389fab
commit 16a05f1a38
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

46
AcWing/835/835.cpp Normal file
View File

@ -0,0 +1,46 @@
#include <bits/stdc++.h>
using namespace std;
int n;
char op;
string s;
struct node {
int val;
node* next[30];
~node() {
for (auto i : next) {
delete i;
}
}
};
void insert(node* root, string s) {
if (s.empty()) {
root->val++;
return;
}
if (root->next[s[0] - 'a'] == nullptr) root->next[s[0] - 'a'] = new node();
insert(root->next[s[0] - 'a'], s.substr(1));
}
int query(node* root, string s) {
return s.empty() ? root->val : (root->next[s[0] - 'a'] == nullptr ? 0 : query(root->next[s[0] - 'a'], s.substr(1)));
}
int main() {
node* root = new node();
cin >> n;
for (int i = 0; i < n; i++) {
cin >> op >> s;
if (op == 'I') {
insert(root, s);
} else {
cout << query(root, s) << endl;
}
}
delete root;
return 0;
}