zoukankan      html  css  js  c++  java
  • 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
    ",kmp(str2,str1,next));
        }
        return 0;
    }        
  • 相关阅读:
    连接查询
    使用聚合函数查询
    mysql 查询数据
    Mysql的基本操作
    MySQL的数据类型
    Mysql简介及安装教程
    客户端-服务端
    configparser模块
    反射
    class_method和static_method
  • 原文地址:https://www.cnblogs.com/chaosheng/p/4943047.html
Copyright © 2011-2022 走看看