ecnu 3441 Kmp

#include<bits/stdc++.h>
using namespace std;

int kmp(string& t,string& p){   //从t中找p出现的次树
    int* next=new int[p.size()+5];
    next[0]=next[1]=0;
    int cnt=0,lent=t.size(),lenp=p.size();
    for(int i=1;i<lenp;i++){
        int j=next[i];
        while(j>0&&p[i]!=p[j])j=next[j];
        next[i+1]=p[i]==p[j]?j+1:0;
    }
    for(int i=0,j=0;i<lent;i++){
        while(j>0&&t[i]!=p[j])j=next[j];
        if(t[i]==p[j])j++;
        if(j==lenp){
            j=next[j];
            cnt++;
        }
    }
    return cnt;
}

int main(){
    string t,p;
    cin>>t;
    int n,u,l,r;
    cin>>n;
    while(n--){
        cin>>l>>r>>p;
        string sub(t.substr(l,r-l+1));
        int res=kmp(sub,p);
        cout<<res<<endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/TAMING/p/9202205.html
kmp