改进的模式匹配算法——KMP算法

来源:互联网 发布:机器人编程下载有哪些 编辑:程序博客网 时间:2024/05/17 21:52

目录

  • 目录
  • 概述
  • next数组求解算法
  • KMP算法

概述

KMP算法可以在O(n+m)的时间数量级上完成串的模式匹配操作。其改进在于:每当一趟匹配过程中出现字符比较不等时,不需回溯i指针,而是利用已经得到的“部分匹配”的结果将模式向右“滑动”尽可能远的一段距离后,继续进行比较。

这里我假设你已经知道有next数组的存在了,那么,next数组的实质是什么呢?next数组实质上就是:每个位置找到最长的公共前缀

next数组求解算法

void getNext(string& tmp, vector<int>& next){    int i = 1, j = 0;    int len = tmp.size();    cout << len << endl;    next.resize(len + 1);    next[i] = 0;    while (i <= len)    {//      if (i > 0 && (i - 1) < len && j > 0 && (j - 1) < len)//          cout << i << ", " << j << ": " << tmp[i - 1] << " " << tmp[j - 1] << endl;//      else//          cout << i << ", " << j << endl;        if (j == 0 || tmp[i - 1] == tmp[j - 1])        {            ++i;            if (i > len)                break;            next[i] = ++j;        }        else            j = next[j];//利用next自身的性质    }    return;}

KMP算法

int kmp(string& a, string& tmp, vector<int>& next){    int i = 1, j = 1;    int len1 = a.size(), len2 = tmp.size();    while (i <= len1 && j <= len2)    {        if (j == 0 || a[i - 1] == tmp[j - 1])        {            ++i;            ++j;        }        else            j = next[j];    }    if (j > len2)    {        cout << "Match the string!" << endl;        return true;    }    cout << "Match the nothing!" << endl;    return false;}
1 0
原创粉丝点击