#include<fstream>
#include<cstring>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
struct T
{
char c;
int n,p,s,b;
}t[5200001];
char w[21];
int main()
{
for(int v,z=0;cin>>v;) {
cin.getline(w,21);
int l=strlen(w);
if(v>2) {
bool o=1;
int e=0,r=0;
for(int i=1;i<l&&o;++i) {
o=0;
for(int q=t[e].s;q&&!o;q=t[q].b)
if(t[q].c==w[i]&&t[q].p)
++r,e=q,o=1;
}
cout<<r<<'\n';
} else if(v>1) {
bool o=1,f=1;
int q=0;
for(int i=1;i<l&&o&&f;++i) {
o=0;
for(int e=t[q].s;e&&!o&&f;e=t[e].b)
if(t[e].c==w[i]&&t[e].p&&(q=e,o=1,i==l-1))
cout<<t[e].n<<'\n',f=0;
}
if(f)
cout<<"0\n";
} else if(v) {
int q=0;
for(int i=1;i<l;++i)
for(int o=t[q].s;o;o=t[o].b)
if(t[o].c==w[i]&&(--t[o].p,q=o,i==l-1)) {
--t[o].n;
break;
}
} else {
int r=0,b=0;
bool g=1;
for(int p=1;p<l&&g;++p) {
bool f=0;
for(int o=t[r].s;o&&!f&&g;o=t[o].b)
if(t[o].c==w[p]) {
if(++t[o].p,r=o,f=1,p==l-1)
++t[o].n,g=0;
} else
b=o;
if(!f&&g)
t[++z].c=w[p],t[z].n=p==l-1,t[z].p=1,t[r].s?t[b].b=z:t[r].s=z,r=z;
}
}
}
return 0;
}