以后KMP就按照这个方式写了。看了kuangbin的写法
2015-08-12 10:42
423 查看
/* pku3461(Oulipo), hdu1711(Number Sequence) 这个模板 字符串是从0开始的 Next数组是从1开始的 */ #include <iostream> #include <cstring> using namespace std; const int N = 1000002; int next ; char S , T ; int slen, tlen; void getNext() { int j, k; j = 0; k = -1; next[0] = -1; while(j < tlen) if(k == -1 || T[j] == T[k]) next[++j] = ++k;//表示T[j-1]和T[k-1]相匹配,当j处失配时,直接用next[j]处来匹配当前失配处 else k = next[k]; } /* 返回模式串T在主串S中首次出现的位置 返回的位置是从0开始的。 */ int KMP_Index() { int i = 0, j = 0; getNext(); while(i < slen && j < tlen) { if(j == -1 || S[i] == T[j]) { i++; j++; } else j = next[j]; } if(j == tlen) return i - tlen; else return -1; } /* 返回模式串在主串S中出现的次数 */ int KMP_Count() { int ans = 0; int i, j = 0; if(slen == 1 && tlen == 1) { if(S[0] == T[0]) return 1; else return 0; } getNext(); for(i = 0; i < slen; i++) { while(j > 0 && S[i] != T[j]) j = next[j]; if(S[i] == T[j]) j++; if(j == tlen) { ans++; j = next[j]; } } return ans; } int main() { int TT; int i, cc; cin>>TT; while(TT--) { cin>>S>>T; slen = strlen(S); tlen = strlen(T); getNext(); for(int i=0;i<=tlen;i++) cout<<next[i]<<" "; cout<<endl; cout<<"模式串T在主串S中首次出现的位置是: "<<KMP_Index()<<endl; cout<<"模式串T在主串S中出现的次数为: "<<KMP_Count()<<endl; } return 0; } /* 3 ababcabcacbabcac abcac */
相关文章推荐
- Hdoj 1014 Uniform Generator
- VC中程序最小化到托盘
- linux下select,poll,epoll的使用与重点分析
- LeetCode题解:Implement Queue using Stacks
- 请求参数的中文乱码问题
- 2015-2016流行的php面试题及答案
- 文件下载
- codeforces 235 B. Let's Play Osu!
- hdu5379||2015多校联合第7场1011 树形统计
- iOS- JSon和Xml解析,与服务器交互数据的解析详解与使用,各种解析方式详解
- MySQL备份与恢复之热备(3)
- Verilog inout 双向口使用和仿真
- caffe protobuf介绍
- 学编程?重要?!
- convertView&setTag方法的一点理解
- hdu 5371 Hotaru's problem(manacher+尺取法)
- CentOS7给终端配置快捷键
- jdk 包 介绍
- SQL Server 中关于EXCEPT和INTERSECT的用法
- 《大脑活用学习法》读书笔记