KMP模板
2015-11-02 23:28
302 查看
判断子串个数 #include<bits/stdc++.h> using namespace std; int next[10000]; int get_next(char s[]) { int len=strlen(s); int i=0,j=-1; next[0]=-1; while(i<len) //i<len { if(j==-1||s[i]==s[j]) { i++;j++; if(s[i]!=s[j]) next[i]=j; else next[i]=next[j]; } else j=next[j]; } } int index_kmp(char s[],char c[]) { get_next(c); int len=strlen(s); int len1=strlen(c); int i=0,j=0,ans=0; while(i<len) { //cout<<i; if(j==-1||s[i]==c[j]) { i++;j++; } else j=next[j]; if(j>=len1) //统计子串在母串中的个数,可重叠 ababa aba 2 { ans++; j=next[j]; //j=0 ; //统计子串在母串中的个数,不重叠ababa aba 1 } } return ans; } char s[100],c[199]; int main() { while(~scanf("%s%s",s,c)) { int num=index_kmp(s,c); printf("%d\n",num); } }
查找是否为子串
#include<bits/stdc++.h> using namespace std; int next[10000]; int get_next(char s[]) { int len=strlen(s); int i=0,j=-1; next[0]=-1; while(i<len) //i<len { if(j==-1||s[i]==s[j]) { i++;j++; if(s[i]!=s[j]) next[i]=j; else next[i]=next[j]; } else j=next[j]; } } int index_kmp(char s[],char c[]) { get_next(c); int len=strlen(s); int len1=strlen(c); int i=0,j=0,ans=0; while(i<len) { //cout<<i; if(j==-1||s[i]==c[j]) { i++;j++; } else j=next[j]; if(j>=len1) break; } if(j>=len1) return i-len1+1; else return -1; } char s[100],c[199]; int main() { while(~scanf("%s%s",s,c)) { int num=index_kmp(s,c); printf("%d\n",num); } }
相关文章推荐
- maven镜像
- 浅谈JavaScript中的跨域解决方案
- Google Interview Questions: Software Engineer
- 微信开发之客服消息的使用
- 12 个非常实用的 jQuery 代码片段
- Mahout随机森林算法--分类无标签数据
- 使用 dd 命令进行硬盘 I/O 性能检测
- select下拉联动 (Bootstrap、JQuery插件之cxselect)
- C#学习笔记 常用的集合
- Google Interview Questions: Software Engineer
- XMPP框架 微信项目开发之CoreData学习——CoreData的多表关联操作
- Json使用整理
- 最大生成树(Greedy Algorithm)
- OC06 数组高级
- 【安卓开发问题解决】logcat信息一闪而过的解决方法
- OC06 Block
- HDU 5515 Game of Flying Circus 二分
- HDU 5536 Chip Factory (暴力 或者 01Trie)
- 桥接模式与适配器模式辨析
- BFS Codeforces591E Three States