思路:关键是用一个数组记录母串中当前所指字符与子串相匹配字符的长度。kmp思想,当母串中出现一次子串时,j跳到子串pos[i-len2]的位置接着与母串i所指的下一个字符比较。
(wawawawawawaac)
Censor
frog is now a editor to censor so-called sensitive words (敏感词).
She has a long text pp. Her job is relatively simple -- just to find the first occurence of sensitive word ww and remove it.
frog repeats over and over again. Help her do the tedious work.
Input
The input consists of multiple tests. For each test:
The first line contains 11 string ww. The second line contains 11 string pp.
(1≤length of w,p≤5⋅1061≤length of w,p≤5⋅106, w,pw,p consists of only lowercase letter)
Output
For each test, write 11 string which denotes the censored text.
Sample Input
abc
aaabcbc
b
bbb
abc
ab
Sample Output
a
ab
#include<iostream>
#include<cstring>
#include<string>#include<cstdio>
using namespace std;
const int maxn=5000005;
char s1[maxn],s2[maxn];
int pos[maxn];
int nextt[maxn];
char las[maxn];
int len1,len2 ;
using namespace std;
void GetNext()
{ int i=0,j=-1;
nextt[0]=-1;
while(s2[i]!='\0')
{
if(j==-1 || s2[i]==s2[j])
{
i++;
j++;
nextt[i]=j;
}
else
j=nextt[j];
}
}
int main()
{
while(~scanf("%s %s",s2,s1))//s2 子串,s1 母串
{len1 = strlen(s1);
len2 = strlen(s2);
GetNext();
int k=0;
int i=0;
int j=0;
while(i < len1)
{
las[k]=s1[i];
while(j!=-1 && las[k]!=s2[j])
j=nextt[j];
i++;
j++;
pos[k++]=j; //记录匹配到k位置时对应的成功匹配到了的子串字符数目.
if(j==len2)
{
k-=len2; //相当于删除。
j=pos[k-1]; 子串跳转的位置。
}
}
las[k] = '\0';
printf("%s\n",las);
}
}