Step1 Problem:
给你 n 个单词,一个文本串。
问你每个单词在文本串中出现的次数(可重叠),没有出现过的不需要输出。
数据范围:
1<=单词长度<=50, 1<=n<=1000, 文本串 <= 2e6.
Step2 Ideas:
匹配的时候,需要判断该后缀是否也是一个单词,所以需要走到 fail 指针所指位置。
Step3 Code:
#include<bits/stdc++.h>
using namespace std;
const int N = 5e4+50;
const int M = 2e6+5;
struct node
{
int id;
node *next[26], *fail;
};
node a[N];
char str[1005][55];
char s[M];
int ans[1005];
int top;
node *creat_kong()
{
node *root = &a[top++];
root->id = 0;
for(int i = 0; i < 26; i++)
root->next[i] = NULL;
root->fail = NULL;
return root;
}
void Insert(node *root, char *s, int id)
{
node *p = root;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
int tmp = s[i] - 'A';
if(!p->next[tmp]) p->next[tmp] = creat_kong();
p = p->next[tmp];
}
p->id = id;
}
void get_fail(node *root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node *p = q.front(); q.pop();
for(int i = 0; i < 26; i++)
{
if(!p->next[i]) continue;
node *tmp = p->fail;
while(tmp && !tmp->next[i]) tmp = tmp->fail;
if(!tmp) p->next[i]->fail = root;
else p->next[i]->fail = tmp->next[i];
q.push(p->next[i]);
}
}
}
void mat(node *root, char *s)
{
int len = strlen(s);
node *p = root;
for(int i = 0; i < len; i++)
{
if(s[i] < 'A' || s[i] > 'Z') {
p = root;
continue;
}
int tmp = s[i]-'A';
while(p != root && !p->next[tmp]) p = p->fail;
if(p == root && !p->next[tmp]) continue;
p = p->next[tmp];
node *t = p;
while(t != root)
{
if(t->id)//判断当前位置对应的单词是否存在
ans[t->id]++;
t = t->fail;
}
}
}
int main()
{
int n;
while(~scanf("%d", &n))
{
top = 0;
node *root = creat_kong();
for(int i = 1; i <= n; i++)
{
scanf("%s", str[i]);
Insert(root, str[i], i);
}
get_fail(root);
memset(ans, 0, sizeof(ans));
scanf("%s", s);
mat(root, s);
for(int i = 1; i <= n; i++)
{
if(ans[i]) printf("%s: %d\n", str[i], ans[i]);
}
}
return 0;
}