censoring

Farmer John has purchased a subscription to Good Hooveskeeping magazine for his cows, so they have plenty of material to read while waiting around in the barn during milking sessions. Unfortunately, the latest issue contains a rather inappropriate article on how to cook the perfect steak, which FJ would rather his cows not see (clearly, the magazine is in need of better editorial oversight).

FJ has taken all of the text from the magazine to create the string S of length at most 10^6 characters. From this, he would like to remove occurrences of a substring T to censor the inappropriate content. To do this, Farmer John finds the _first_ occurrence of T in S and deletes it. He then repeats the process again, deleting the first occurrence of T again, continuing until there are no more occurrences of T in S. Note that the deletion of one occurrence might create a new occurrence of T that didn't exist before.

Please help FJ determine the final contents of S after censoring is complete

有一个S串和一个T串,长度均小于1,000,000,设当前串为U串,然后从前往后枚举S串一个字符一个字符往U串里添加,若U串后缀为T,则去掉这个后缀继续流程。

Input
The first line will contain S. The second line will contain T. The length of T will be at most that of S, and all characters of S and T will be lower-case alphabet characters (in the range a..z).
Output
The string S after all deletions are complete. It is guaranteed that S will not become empty during the deletion process.


Sample Input
whatthemomooofun   //s串,母串

moo  //T串,模式串
Sample Output
whatthefun  //s[10..12]="moo",消掉,再进入一个‘o’,s[8..10]="moo",又消掉。

sol:s串为母串,依次进栈,与模式串T进行匹配,若匹配失败,模式串j的值回退,若匹配成功,则用num数组记录下母串的第i位匹配到的字符在模式串中的位置(这是为了找到模式串后,继续匹配时,j如何变)。如果模式串匹配成功,则将s中的T串出栈,出栈后j的值变为当前栈顶元素所匹配到的字符在模式串中的位置。

代码如下:

 1 #include<cstdio>
 2 #include<cstring>
 3 using namespace std;
 4 const int maxn=1000050;
 5 int top,n,m;
 6 char s1[maxn],s2[maxn];
 7 int sta[maxn],num[maxn],nxt[maxn];
 8 void getnxt()
 9 {
10   for(int i=2,j=0;i<=m;i++)
11   {
12     while(j&&s2[j+1]!=s2[i])
13           j=nxt[j];
14     if(s2[j+1]==s2[i])
15        j++;
16     nxt[i]=j;
17   }
18 }
19 int main(){
20   scanf("%s%s",s1+1,s2+1);
21   n=strlen(s1+1);//母串长度 
22   m=strlen(s2+1);//子串长度 
23   getnxt();//求出子串的next数组 
24   for(int i=1,j=0;i<=n;i++)
25   {
26       sta[++top]=i;
27     while(j&&s2[j+1]!=s1[i]) 
28     //当母串的第i个与子串的第j+1个不匹配时 
29          j=nxt[j];
30     if(s2[j+1]==s1[i])
31         j++;
32     num[i]=j;//母串的第i个可匹配到子串的第j个位置 
33     
34     if(j==m)
35     {
36         top-=m;
37         j=num[sta[top]];//j变为栈顶元素匹配到的子串的位置 
38     }
39   }
40   for(int i=1;i<=top;i++)
41       printf("%c",s1[sta[i]]);
42  // puts("");
43   return 0;
44 }
原文地址:https://www.cnblogs.com/cutepota/p/12562334.html