SCU - 4438 KMP

Censor

frog is now a editor to censor so-called sensitive words (敏感词).

She has a long text (p). Her job is relatively simple – just to find the first occurence of sensitive word (w) 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 (1) string (w). The second line contains (1) string (p).

((1 \leq \textrm{length of}\ w, p \leq 5 \cdot 10^6), (w, p) consists of only lowercase letter)

Output

For each test, write (1) string which denotes the censored text.

Sample Input

abc
aaabcbc
b
bbb
abc
ab

Sample Output

a

ab

这道题用KMP写,可以用栈或vector把没有匹配的和匹配失败的位置存下来,这种思想很巧妙。。。。。
KMP的NEXT数组还是不太懂,自己还是太菜,这次写这道题ce了n次,这让我深深的明白了变量名尽量不要用完整的英文单词

上代码

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define INF 0x3f3f3f3f
int nexxt[100010];
string a,b;
void solvee()
{
    int len=b.length();
    nexxt[0]=0;
    int q=0,k=0;
    for(int i=1;iwhile(k>0&&b[i]!=b[k])
        k=nexxt[k-1];
        if(b[k]==b[i])
        k++;
        nexxt[i]=k;

    }


}
struct node
{
    char aa;
    int val;
    //node(char x,int w):aa(x),val(w){}
};
void kmp()
{   solvee();
    int lena=a.length();
    int lenb=b.length();
    int k=0;
//  stackq;
        vectorq;
    for(int i=0;iwhile(k>0&&a[i]!=b[k])
        k=nexxt[k-1];
        if(a[i]==b[k])
        {
            k++;
        }
        q.push_back((node){a[i],k});
        if(k==lenb)
        {
            int t=lenb;
            while(t--)
            {
                q.pop_back();
             } 
             if(q.empty()) k=0;
             else k=q.back().val; 
        }



    }

//  if(!q.empty())
//  stackqq;
    if(!q.empty())  
    {   int ll=q.size();
        for(int i=0;icout<cout<int main()
{
    ios::sync_with_stdio(false);  //不加会超时 
    while(cin>>b>>a)
    kmp(); 


    return 0;
}

你可能感兴趣的:(kmp)