KMP习题集

模板题
剪花布条
AC代码

#include <bits/stdc++.h>
using namespace std;
void getNext(char p[],int Next[]){
    Next[0]=-1;
    int i=0,j=-1;
    int n=strlen(p);
    while(i<n){
        if(j==-1||p[i]==p[j]){
            i++;
            j++;
            Next[i]=j;
        }
        else
            j=Next[j];
    }
}
int KMP(char t[],char p[],int Next[]){
    int i=0,j=0;
    int n1=strlen(t);
    int n2=strlen(p);
    while(i<n1&&j<n2){
        if(j==-1||t[i]==p[j]){
            i++;
            j++;
        }
        else
            j=Next[j];
    }
    if(j==n2)
        return i;
    else
        return -1;
}
int main(){
    while(1){
        char t[1005],p[1005];
        int Next[1005];
        scanf("%s",t);
        if(t[0]=='#'){
            break;
        }
        scanf("%s",p);
        int len=strlen(t),cnt=1;
        getNext(p,Next);
        int loc=KMP(t,p,Next);
        if(loc==-1){
            printf("0\n");
            continue;
        }
        else if(loc==len){
            printf("1\n");
            continue;
        }
        else{
            while(1){
                int val=KMP(t+loc,p,Next);
                if(val==-1) break;
                loc=val+loc;
                cnt++;
            }

            printf("%d\n",cnt);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44412226/article/details/89737501