hdoj 1686 kmp
#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;}
}
}
最新文章
- js事件代理(委托)
- Nginx模块之———— RTMP模块 统计某频道在线观看流的客户数
- 走读openwrt的shell的总结【转】
- 第二百九十八天 how can I 坚持
- Word添加新编号
- MySQL(14):Select-limit(限制获得的记录数量)
- C#语音录制
- python学习===从一个数中分解出每个数字
- 优先级队列Priority_queue
- 主键乱序插入对Innodb性能的影响
- wss 协议传送过来的数据是经过 gzip 压缩过的,如何使用 qt 解压该数据呢?
- 基于 CODING 的 Spring Boot 持续集成项目
- Office 2016 自定义安装
- Kubernetes节点维护
- 4.请介绍一下c++和Java的区别
- bzoj 1042
- minifilter
- djang-rest-framework学习-day1
- mysql的逻辑结构
- html05
热门文章
- [FJSC2014]折线统计
- NOIP2014解方程
- Delphi中WideString类型如何转化成String类型
- MVC项目初次发布到IIS可能会遇到的问题
- [cocos2dx 3.0 + ios]如何编写iAd的plugin
- Python中With的用法
- jemalloc/jemalloc.h: No such file or directory
- Xcode7.1与iOS9之坑
- Oracle索引(B*tree与Bitmap)的学习总结
- dijkstra算法(迪杰斯特拉算法)