KMP算法

#include<bits/stdc++.h>
using namespace std;
char A[1007],B[1007];
int P[1007],n,m;
void pre()
{
    P[1]=0;
    int j=0;
    for(int i=1;i<m;i++)
    {
        while(j>0 && B[j+1]!=B[i+1])
            j=P[j];
        if(B[j+1]==B[i+1])
            j++;
        P[i+1]=j;
    }
}
int kmp()
{
    int ans=0,j=0;
    for(int i=0;i<n;i++)
    {
        while(j>0 && 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(scanf("%s%s",A+1,B+1)==2)
    {
        m=strlen(B+1);
        n=strlen(A+1);
        pre();
        cout<<kmp()<<endl;
    }
    return 0;

 

posted @ 2019-08-13 18:58  octal_zhihao  阅读(136)  评论(0编辑  收藏  举报