KMP算法(待优化)--2015年7月25日14:04:25V1.0版
来源:互联网 发布:js怎么截取地址字符串 编辑:程序博客网 时间:2024/06/08 14:34
#include <iostream>#include <string>#include <cstring>using namespace std;void makenext(const string str,int next[]) //next数组{ next[0] = 0; int maxs; //最大前缀后缀相等数目 for(int i = 1,maxs = 0;i < str.length(); i++) { while( maxs > 0 && str.at(maxs) != str.at(i)) //当前缀下一位不等于后缀下一位时 { //当匹配失败时,找到一个前缀序列,再与后缀匹配 //a[0]...a[maxs].... a[i-maxs]...a[i-1] a[i]... // 匹配 匹配 匹配失败 // a[0]....a[max-1] a[max]... // 匹配 判断是否匹配 // a[0]...a[j-1] a[j] maxs = next[maxs - 1]; //next[max - 1]相当于匹配失败后,前缀作为后缀,所对应的前缀 } if(str.at(maxs) == str.at(i)) //如果maxs和i匹配,则最大前缀后缀数目+1 { maxs++; } next[i] = maxs; }// 测试输出// cout<< str << endl;// for(int i = 0; i < str.length(); i++)// cout << next[i] << " ";// cout << endl;}bool KMP(const string motherstr,const string patternstr,int next[]) //KMP算法{ int maxs; //最大前缀后缀相等数目 makenext(patternstr,next); for(int i = 0,maxs = 0; i < motherstr.length(); i++) { while(maxs > 0 && patternstr[maxs] != motherstr[i]) //当前缀下一位不等于后缀下一位时 { //PS:这里的原理和makeNext方法里面一样,只不过这里的模式串是patterntr,母串是mothertr maxs = next[maxs - 1]; } if(patternstr[maxs] == motherstr[i]) //如果maxs和i匹配,则最大前缀后缀数目+1 { maxs++; } if(maxs == patternstr.length()) //当最大前缀后缀相等数目与patternstr一样长时,则证明匹配成功 { //测试匹配成功时,返回patternstr在motherstr里的位置 //cout<<i-maxs+1; return true; } } return false;}int main(){//测试KMP算法是否正确 string str1= "aaaac"; string str2= "aaaa"; int next[100]; if(KMP(str1,str2,next)) cout<<"Yes."<<endl; else cout<<"NO."<<endl; return 0;}
0 0
- KMP算法(待优化)--2015年7月25日14:04:25V1.0版
- 各种排序算法比较--2015年7月23日22:33:43v1.0版
- 各种搜索算法比较--2015年7月26日16:42:45V1.0版
- 简单的字谜游戏--可扩展--2015年7月25日14:58:00V1.1版
- KMP之一:从头到尾彻底理解KMP算法(2014年8月1日版)
- 迷宫问题(栈解决)--2015年8月9日19:23:23v1.0版
- 待解决问题(2011年5月4~27日)
- 7月25日
- 2016年3月1日--3月25日(0小时,剩3152小时)
- 从头到尾彻底理解KMP(2014年8月8日版)(转载)
- 从头到尾彻底理解KMP(2014年8月22日版)
- 从头到尾彻底理解KMP(2014年8月15日版)
- 从头到尾彻底理解KMP(2014年8月22日版)
- 从头到尾彻底理解KMP(2014年8月22日版)
- [置顶] 从头到尾彻底理解KMP(2014年8月22日版)
- 从头到尾彻底理解KMP(2014年8月22日版)
- [置顶] 从头到尾彻底理解KMP(2014年8月22日版)
- 从头到尾彻底理解KMP(2014年8月22日版)
- spring基础
- hdu 5303 Delicious Apples
- android之对话框
- 单队列的链式表示和实现
- HDU 1671 Phone List
- KMP算法(待优化)--2015年7月25日14:04:25V1.0版
- poj 2253 Frogger(最小生成树)
- HDU1565 方格取数(1) 网络流
- 排序算法
- Dubbo--简介
- [Python]import 出错
- [bfs] poj3278 Catch that Cow
- iOS- AVSpeechSynthesizer——iOS7语音合成器
- 完全退出Activity