HDU - 1686 Oulipo [KMP字符串模板

#include "iostream"
#include "algorithm"
#include "cstring"
#include "cstdio"
using namespace std;
string  a,b;
int nextt[10005];

void getnext(int m){
    int i=0,j=-1;
    nextt[0]=-1;
    while(i<b.length()){
        if(j==-1||b[i]==b[j]){
            i++;
            j++;
            nextt[i]=j;
        }
        else
            j=nextt[j];
//        cout<<"i="<<i<<" ";
 //       cout<<"j="<<j<<endl;
    }
}

int KMP(int n,int m){
    int i=0,j=0,ans=0;
    while(i<a.length()){
        if(j==-1||a[i]==b[j]){
            i++;
            j++;
        }
        else j=nextt[j];
    if(j==b.length())
        ans++;
    //cout<<"i="<<i<<endl;
    }
    return ans;
}

int main(){
    std::ios::sync_with_stdio(false);
    int T,n,m;
    cin>>T;
    while(T--){
        cin>>b;
        cin>>a;
        getnext(m);
        printf("%d\n",KMP(n,m));
    }
    return 0;
}

 

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/cheung99857/article/details/81782781
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞