KMP
来源:互联网 发布:mobi格式软件ios 编辑:程序博客网 时间:2024/06/03 12:20
/*KMP算法时间复杂度:O(主串长度加上子串长度)空间复杂度:O(主串长度加上子串长度再加上next数组的长度(与子串长度相同))*/#include <iostream>#include <string>#include <algorithm>using namespace std;void gets_next(string T, int len, int *next){ int i = 1; int j = 0; next[1] = 0; while(i < len) { if(j==0 || T[i-1] == T[j-1]) { ++i; ++j; if(T[i-1]!=T[j-1]) next[i] = j; else next[i] = next[j]; } else j = next[j]; } cout << "next数组如下:" << endl; for(int t = 1; t <= len; t++) cout << next[t] << " "; cout << endl;}int KMP(string S, int len1, string T, int len2, int pos)//pos为起始位{ int i = pos; int j = 1; int next[len2+1]; gets_next(T, len2, next); while(i <= len1 && j <= len2) { if(j==0 || S[i-1] == T[j-1]) { ++i; ++j; if(j > len2)//找到匹配 return i - len2;//返回首位下标 } else { j = next[j]; } } return 0;}int main(){ string str = "aaaaaaab"; string str1 = "aaaaabbaaaaaaabaa"; int num = KMP(str1, str1.size(), str, str.size(), 1); if(num!=0) cout << "子串在主串中的起始位置为 " << num; else cout << "主串不存在与子串相匹配的串"; return 0;}
0 0
- KMP
- KMP
- KMP
- KMP
- KMP
- KMP
- kmp
- kmp
- KMP
- kmp
- KMP
- KMP
- KMP
- kmp
- KMP
- KMP
- kmp
- KMP
- Qt 读写Excel,并显示到tablewidget
- Java连接access
- Linux下eclipse编译C++动态链接库报错问题解决
- 设计模式学习(三)------工厂方法模式
- 黑马程序员-JAVA-交通灯模拟
- KMP
- (总结)Nginx配置文件nginx.conf中文详解
- (转)你只是看起来很努力
- invalidate和postInvalidate的区别
- openfire+asmack搭建的安卓即时通讯(一) 15.4.7
- openfire+asmack搭建的安卓即时通讯(二) 15.4.9
- openfire+asmack搭建的安卓即时通讯(三) 15.4.9
- openfire+asmack搭建的安卓即时通讯(四) 15.4.10
- openfire+asmack搭建的安卓即时通讯(五) 15.4.12