KMP算法


KMP算法


KMP算法学习视频

  1. 「天勤公开课」KMP算法易懂版

  2. 天勤考研数据结构:KMP算法

  3. 懒猫老师-数据结构-(15)KMP算法2-next数组


KMP算法程序实例如下

语言:C/C++

编译运行环境:

Visual Studio 2019

Code:blocks

   	
	#include <iostream>
    #include <stdlib.h>
    #include <cstring>
    using namespace std;

    typedef struct {
        char* ch;
        int length;
    }Str;

    //未改进的KMP算法代码实现
   	void get_next(Str substr, int* next)
    {
        int i = 0, j =  -1;  // i为后缀,j为前缀
        next[0] = -1;
        while (i < substr.length -1) {
            if (j == -1 || substr.ch[i] == substr.ch[j]) {
                i++;
                j++;
                next[i] = j;  
            }
            else {
                j = next[j];
            }
        }
    }

    int KMP(Str str, Str substr, int* next)//利用KMP算法匹配
    {
        int i = 0;
        int j = 0;
        while (i <= str.length && j < substr.length) {
            if (j == -1 || str.ch[i] == substr.ch[j]) {
                i++;
                j++;
            }
            else {
                j = next[j];
            }
        }
        if (j == substr.length)
            return i - substr.length;
        else
            return -1;
    }

    int main(){
        char a[] = "bacbababadababacambabacaddababacasdsd";
        char b[] = "ababaca";

        Str S, T;
        S.length = strlen(a);
        T.length = strlen(b);

        int next[7] = {0,0,0,0,0,0,0};
        S.ch = (char*)malloc(strlen(a) * sizeof(char));
        T.ch = (char*)malloc(strlen(b) * sizeof(char));
        S.ch = a;
        T.ch = b;
        get_next(T, next);
        for (int i = 0; i < 7; i++) {
           cout << next[i] << " ";
        }
        cout << endl;

        cout << KMP(S, T, next);
        return 0;
    }

该算法的难点是如何得到next[]数组,是KMP算法的关键,也是它最巧妙的地方。
get_next()函数算法的思想是"用自己匹配自己",根据next[0],next[1],…,next[i-1]递推next[i],代码和KMP()函数匹配部分非常相似。


学习心得

通过视频学习可以有一个大概的理解,如有不理解的地方还是得通过运行程序,设置断点调试才能有比较清晰得理解。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值