frog is now a editor to censor so-called sensitive words (敏感词).
She has a long text p p. Her job is relatively simple -- just to find the first occurence of sensitive word w w and remove it.
frog repeats over and over again. Help her do the tedious work.
The input consists of multiple tests. For each test:
The first line contains 1 1 string w w. The second line contains 1 1 string p p.
(1≤length of w,p≤5⋅10 6 1≤length of w,p≤5⋅106, w,p w,p consists of only lowercase letter)
For each test, write 1 1 string which denotes the censored text.
abc
aaabcbc
b
bbb
abc
ab
a
ab
题意:给出2个字符串,第一个字符串P是第二个字符串的敏感词,如果第二个字符串出现了P就要删除,后面的字符补到前面去,问最后剩下的字符串是什么
题解:KMP算法,用数组模拟栈储存要输出的字符串,index表示单签储存了几个字符,如果遇到要删除的字符串,则index-P的长度,然后继续更新,关于KMP算法的
话,如果不懂就先网上搜索下资料吧,这个算法我还不能很好地总结.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 5e6 + 5;
int Next[maxn],tmp[maxn];
void makeNext(const char P[]){
int q,k;
int m=strlen(P);
memset(Next,0,sizeof(Next));
Next[0]=0;
for(q=1,k=0;q0&&P[q]!=P[k])
k=Next[k-1];
if(P[q]==P[k]) k++;
Next[q]=k;
}
}
char st[maxn];
int KMP(const char T[],const char P[]){
int n=strlen(T),m=strlen(P),q=0,index=0;
makeNext(P);
for(int i=0;i0&&P[q]!=T[i])
q=Next[q-1];
if(P[q]==T[i]) q++;
tmp[index]=q;//记录第index个字符的部分匹配值
if(q==m) {
index-=m;//匹配成功时,删去最后m个字符,继续匹配
q=tmp[index];//将index的部分匹配值给q
}
}
return index;
}
char st1[maxn],st2[maxn];
int main(){
// freopen("in.txt","r",stdin);
while(~scanf("%s%s",st1,st2)){
st[KMP(st2,st1)]='\0';
printf("%s\n",st);
}
return 0;
}