【KMP模板】【一本通 2.2 例 1】剪花布条

#include<bits/stdc++.h>
using namespace std;
char A[1004],B[1004];
int P[1004],n,m;
inline void pre(){
    P[1]=0;
    int j=0;
    for(int i=1;i<m;i++){
        while(j&&B[j+1]!=B[i+1]) j=P[j];
        if(B[j+1]==B[i+1])j++;
        P[i+1]=j;
    }
}
inline int kmp(){
    int ans=0,j=0;
    for(int i=0;i<n;i++){
        while(j&&B[j+1]!=A[i+1]) j=P[j];
        if(B[j+1]==A[i+1]) j++;
        if(j==m){
            ans++;
            j=0;
        }
    }
    return ans;
}
int main(){
    while(1){
        scanf("%s",A+1);
        n=strlen(A+1);
        if(n==1&&A[1]=='#') break;
        scanf("%s",B+1);
        m=strlen(B+1);
        pre();
        printf("%d\n",kmp());
    }
}

猜你喜欢

转载自www.cnblogs.com/wifimonster/p/10162476.html