经典算法之KMP算法及其优化
来源:互联网 发布:idea查看源码快捷键 编辑:程序博客网 时间:2024/05/16 06:02
KMP算法的具体分析见http://blog.csdn.net/wardseptember/article/details/78801491/
/************************author's email:wardseptember@gmail.comdate:2017.12.18KMP算法************************/#include<iostream>#include <stdio.h>using namespace std;#define maxSize 50void getnext(char substr[], int next[]);//求next[]数组void getnextval(char substr[], int nextval[]);//优化求next[]数组int KMP(char str[], char substr[], int next[]);//KMP算法int main() { char str[50] = "ABABCABCACBAB"; char substr[50] = "ABCAC"; int next[maxSize] = {0}; int nextval[maxSize] = { 0 }; int result1,result2; //KMP算法 getnext(substr, next); result1 = KMP(str, substr, next); cout << "KMP算法匹配结果:" << endl; if (result1 != -1) cout << "主串与子串在主串的第" << result1 << "个字符(首字符的位置为0)处首次匹配" << endl; else cout << "无匹配子串" << endl; //KMP算法的优化 getnextval(substr, nextval); result2 = KMP(str, substr, nextval); cout << "KMP优化算法匹配结果:" << endl; if (result2 != -1) cout << "主串与子串在主串的第" << result2 << "个字符(首字符的位置为0)处首次匹配" << endl; else cout << "无匹配子串" << endl; return 0;}void getnext(char substr[], int next[]) {//求next[]数组 int i = 0, j = -1; next[0] = -1; while (i < strlen(substr) ) { if (j == -1 || substr[i] == substr[j]) { ++i; ++j; next[i] = j; } else j = next[j]; }}void getnextval(char substr[], int nextval[]) {//优化求next[]数组 int i = 0, j = -1; nextval[0] = -1; while (i < strlen(substr)) { if (j == -1 || substr[i] == substr[j]) { ++i; ++j; if (substr[i] != substr[j]) nextval[i] = j; else nextval[i] = nextval[j]; } else j = nextval[j]; }}int KMP(char str[], char substr[], int next[]) { int i = 0, j = 0; while (i < strlen(str)&&j < strlen(substr)) { if (j == 0 || str[i] == substr[j]) { ++i; ++j; } else j = next[j]; } if (j > strlen(substr) - 1) return i - strlen(substr) ; else return -1;}
程序测试结果:
以上如有错误请指出,大家共同学习进步。
阅读全文
0 0
- 经典算法之KMP算法及其优化
- KMP算法及其优化
- KMP算法及其优化
- KMP算法及其优化算法
- 经典算法之Shell排序及其优化
- 字符串查找(KMP算法及其优化)
- KMP算法的一些误区及其优化
- 经典算法之直接插入排序及其优化
- KMP及其改进算法
- kmp算法及其拓展
- KMP算法及其实现
- KMP及其改进算法
- KMP算法及其应用
- KMP经典算法
- 经典KMP算法回顾
- KMP 算法 ---经典
- KMP算法经典讲解
- KMP经典算法解析
- w7,32位远程连接Firebird数据库文件
- 初探Java中JVM的类加载机制之原理简析
- zblog仿站zblog网站制作zblog模板开发zblog主题模板修改
- make的时候出现:ln: 无法创建符号链接" ...... ": 不支持的操作
- linux下的ssh的登录
- 经典算法之KMP算法及其优化
- 每日韩语:韩国年轻人婚礼形式的新趋势
- c实现的printf函数
- 湖北民族学院oj2159 之 页码的数字统计
- HTTP Status 500
- leetcode 554. Brick Wall 使用Map遍历统计
- 内联汇编简介
- python str转bytes
- beego获取ajax数据