经典算法之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;}

程序测试结果:
这里写图片描述

以上如有错误请指出,大家共同学习进步。

原创粉丝点击