KMP算法,查询匹配串的个数

想不到时隔两年回来重新学习KMP算法还是那么难,不过理解了大概,把例程贴上来,如果是求数量只需要加个count变量记录即可。

#include"stdio.h"
#include"string.h"

void makeNext(const char P[],int next[])
{
    int q,k;
    int m=strlen(P);
    next[0]=0;
    for(q=1,k=0;q<m;q++)
    {
        while(k>0&&P[q]!=P[k])
            k=next[k-1];
        if(P[q]==P[k])
        {
            k++;
        }
        next[q]=k;
    }
}

int kmp(const char T[],const char P[],int next[])
{
    int n,m;
    int i,q,count=0;
    n=strlen(T);
    m=strlen(P);
    makeNext(P,next);
    for(i=0,q=0;i<n;i++)
    {
        while(q>0&&P[q]!=T[i])
            q=next[q-1];
        if(P[q]==T[i])
        {
            q++;
        }
        if(q==m)
            count++;
    }
    return count;
}

int main( )
{
    int n,next[10005];
    char str1[10005],str2[1000005];
    scanf("%d",&n);
    while(n--)
    {
        memset(next,0,sizeof(next));
        scanf("%s",str1);
        scanf("%s",str2);
        printf("%d\n",kmp(str2,str1,next));
    }
    return 0;
}        

 

posted @ 2015-11-06 16:46  朝圣の路  阅读(325)  评论(0编辑  收藏  举报