题目:
 
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;}
    }
}

最新文章

  1. js事件代理(委托)
  2. Nginx模块之———— RTMP模块 统计某频道在线观看流的客户数
  3. 走读openwrt的shell的总结【转】
  4. 第二百九十八天 how can I 坚持
  5. Word添加新编号
  6. MySQL(14):Select-limit(限制获得的记录数量)
  7. C#语音录制
  8. python学习===从一个数中分解出每个数字
  9. 优先级队列Priority_queue
  10. 主键乱序插入对Innodb性能的影响
  11. wss 协议传送过来的数据是经过 gzip 压缩过的,如何使用 qt 解压该数据呢?
  12. 基于 CODING 的 Spring Boot 持续集成项目
  13. Office 2016 自定义安装
  14. Kubernetes节点维护
  15. 4.请介绍一下c++和Java的区别
  16. bzoj 1042
  17. minifilter
  18. djang-rest-framework学习-day1
  19. mysql的逻辑结构
  20. html05

热门文章

  1. [FJSC2014]折线统计
  2. NOIP2014解方程
  3. Delphi中WideString类型如何转化成String类型
  4. MVC项目初次发布到IIS可能会遇到的问题
  5. [cocos2dx 3.0 + ios]如何编写iAd的plugin
  6. Python中With的用法
  7. jemalloc/jemalloc.h: No such file or directory
  8. Xcode7.1与iOS9之坑
  9. Oracle索引(B*tree与Bitmap)的学习总结
  10. dijkstra算法(迪杰斯特拉算法)