经典算法之KMP算法及其优化

KMP算法的具体分析见http://blog.csdn.net/wardseptember/article/details/78801491/

/************************
author's email:wardseptember@gmail.com
date:2017.12.18
KMP算法
************************/
#include<iostream>
#include <stdio.h>
using namespace std;
#define maxSize 50
void 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;
}

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值