zoukankan      html  css  js  c++  java
  • hdoj 1686 kmp

    题目:
     
    Sample Input
    3
    BAPC
    BAPC
    AZA
    AZAZAZA
    VERDI
    AVERDXIVYERDIAN
     
    Sample Output
    1
    3
    0
     
     
    代码:
     

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int maxn1=1000010;
    const int maxn2=10010;
    int n,m;
    char a[maxn1];
    char b[maxn2];
    int next[maxn2];
    int main()
    {
     int kmp ( char *a,char *b,int *next);//相应的类型必须改为char型
     int t;
     cin>>t;
     while(t--)
     {
      cin>>b;//先输入短串即串2
      cin>>a;
      n=strlen(a);
      m=strlen(b);
      int ans=kmp(a,b,next);
      cout<<ans<<endl;
     }
     return 0;
    }


    //此函数用来求匹配串s串的next数组
    void getnext (char *s,int *next)
    {
        next[0]=next[1]=0;
        for (int i=1;i<m;i++)//m为匹配串s的长度
     {
            int j=next[i];
            while (j&&s[i]!=s[j])
                j=next[j];
            next[i+1]=s[i]==s[j]?j+1:0;
        }
    }
    //此函数用来计算串b在串a中出现的次数(a中的字母可以重复利用)
    int kmp (char *a,char *b,int *next)
    {
     int times=0;
        getnext (b,next);/////////
        int j=0;
        for (int i=0;i<n;i++)
     {/////n为串1的长度
            while (j&&a[i]!=b[j])
                j=next[j];
            if (a[i]==b[j])
                j++;
            if (j==m)//m为串2的长度
      {
       times++;j=next[j];//加了一个计数器和j=next[j]
      }
      if(i==n-1)
      {return times;}
        }
    }


     

  • 相关阅读:
    GoogleTest初探(2)
    GoogleTest初探(1)
    GoogleMock初探(0)
    GoogleTest初探(0)
    [leetcode] 二叉树的前序,中序,后续,层次遍历
    关于phpmyadmin报403错误forbidden
    如何使用Fiddler抓取Android手机数据请求
    安全性测试之安装包测试
    二代身份证号码编码规则
    Excel导入功能测试用例整理
  • 原文地址:https://www.cnblogs.com/weiyikang/p/3869717.html
Copyright © 2011-2022 走看看