KMP算法(待优化)--2015年7月25日14:04:25V1.0版
2015-07-25 14:31
543 查看
#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; }
相关文章推荐
- 某物流集团企业信息化案例介绍
- 使用Eclipse编写Python
- 在ubuntu12.4系统上安装及配置云服务器OwnCloud 实操笔记
- “Thinking in AngularJS” if I have a jQuery background?
- android之对话框
- Knockout 事件传递参数的方法
- hdu 5303 Delicious Apples
- java 用 _id 查找 MongoDB 下的数据
- 三大抽样分布
- 设计模式_门面模式
- leetcode[137]:Single Number II
- 高可用集群技术理论基础知识
- ls命令的简单实现
- PAT (Advanced Level) 1043. Is It a Binary Search Tree (25) 判断序列是否为BST的先序遍历,递归
- QueryPerformanceFrequency()
- POJ 2065 SETI(高斯消元)
- java新手笔记21 接口
- HDU 5303 Delicious Apples 美味苹果 (DP)
- [黑马程序员](第19天)一些遗漏的知识点
- 设计模式_观察者模式