mirror of
https://git.sb/baoshuo/OI-codes.git
synced 2024-11-08 15:18:46 +00:00
835. Trie字符串统计
https://www.acwing.com/problem/content/submission/code_detail/7680320/
This commit is contained in:
parent
9028389fab
commit
16a05f1a38
46
AcWing/835/835.cpp
Normal file
46
AcWing/835/835.cpp
Normal 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;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user