这道题主要就是本题需要注意的地方是可重叠匹配,直接上模板就好,在字典树id上做点小手脚换为字串的ID,在最后匹配的时候非大写英文字母我们直接让返回到root就可以,其他的就没什么了。上代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<malloc.h>
using namespace std;
char str[2000005];
int cnt[1005]; //此数组存该序号的字串出现的次数
struct node{
int cnt; //存字串id
node *next[30];
node *fail;
node(){
cnt=0;
memset(next,NULL,sizeof(next));
fail=NULL;
}
};
node *root;
void insert(char str[],int num){
int i;
node *p=root;
int len=strlen(str);
for(i=0;i<len;i++){
int index=str[i]-'A';
if(p->next[index]==NULL){
p->next[index]=new node();
p=p->next[index];
}
else p=p->next[index];
}
p->cnt=num;
}
void GetFail(){
int i;
node *p=root;
queue<node *>q;
q.push(root);
while(!q.empty()){
p=q.front();
q.pop();
for(i=0;i<26;i++){
if(p->next[i]==NULL)continue;
q.push(p->next[i]);
if(p==root)p->next[i]->fail=root;
node *temp=p->fail;
while(temp!=NULL){
if(temp->next[i]!=NULL){
p->next[i]->fail=temp->next[i];
break;
}
else temp=temp->fail;
if(temp==NULL)p->next[i]->fail=root;
}
}
}
}
void Query(char str[]){
node *p=root;
int len=strlen(str);
int i;
for(i=0;i<len;i++){
int index=str[i]-'A';
if(index<0||index>25)index=26;
while(p->next[index]==NULL&&p!=root){
p=p->fail;
}
if(p->next[index]==NULL)continue;
p=p->next[index];
node *temp=p;
while(temp->cnt!=0&&temp!=root){
cnt[temp->cnt]++; //注意这儿不应该将temp->cnt的值赋为0,因为AAA中AA的出现次数为2而不是1
temp=temp->fail;
}
}
}
int main()
{
int i,n;
char str1[1002][52];
while(scanf("%d",&n)!=EOF){
root=new node();
memset(cnt,0,sizeof(cnt));
for(i=1;i<=n;i++){
scanf("%s",str1[i]);
insert(str1[i],i);
}
GetFail();
scanf("%s",str);
Query(str);
for(i=1;i<=n;i++){
if(cnt[i]>0)
printf("%s: %d\n",str1[i],cnt[i]);
}
}
return 0;
}