#include <fstream>
#include <cstring>
using namespace std;
struct Trie {
int final = 0, n = 0;
Trie* v[26] {};
} *root = new Trie;
void add(char* s) {
Trie* current = root;
int l = strlen(s);
for(int i = 0; i < l; ++i) {
if(current -> v[s[i] - 'a'] == NULL) {
current -> v[s[i] - 'a'] = new Trie;
++current -> n;
}
current = current -> v[s[i] - 'a'];
}
++current -> final;
}
bool remove(char* s, Trie* current) {
if(s[0] == '\0')
--current -> final;
else if(remove(s+1, current -> v[s[0] - 'a'])) {
--current -> n;
current -> v[s[0] - 'a'] = NULL;
}
if(current -> final == 0 && current -> n == 0 && current != root) {
delete current;
return 1;
}
return 0;
}
int count(char* s) {
Trie* current = root;
int l = strlen(s);
for(int i = 0; i < l; ++i)
if(current -> v[s[i] - 'a'])
current = current -> v[s[i] - 'a'];
else
return 0;
return current -> final;
}
int prefix(char* s) {
Trie* current = root;
int i = 0, l = strlen(s);
while(current -> v[s[i] - 'a'] && i < l) {
current = current -> v[s[i] - 'a'];
++i;
}
return i;
}
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
int op;
char s[21];
while(fin >> op >> s)
if(op == 0)
add(s);
else if(op == 1)
remove(s, root);
else if(op == 2)
fout << count(s) << '\n';
else
fout << prefix(s) << '\n';
}