KMP匹配算法

举例来说,有一个字符串"BBCABCDABABCDABCDABDE",我想知道,里面是否包含另一个字符串"ABCDABD"?

KMP匹配算法代码实现:

#include <string>

#include <vector>

#include <queue>

#include <iostream>

#include <stdio.h>

 

using namespace std;

 

vector<int> GetNext(const string &str)

{

   vector<int> next({-1});//以-1开始

   for(int i=1;i<= str.size();i++)

   {

       int maxLen=0;
//       std::string tmp = str.substr(0,i);//子串计算
       for(int k = 1;k < i;++k)//计算前缀后缀的值
       {
           if(str.substr(0,k)==str.substr(i-k,k))//前缀后缀
           {
               maxLen=k;
           }
       }
       next.push_back(maxLen);

   }

   next.pop_back();

   return next;//ABCDABD    -1 0 0 0 0 1 2;

}

 

int KmpSearch(const string& s, const string& p)

{

    int sLen = s.size();

    int pLen = p.size();

    if (sLen == 0 || pLen == 0)return -1;

    vector<int> next = GetNext(p);

    int i = 0;

    int j = 0;

    while (i < sLen && j < pLen)

    {

        j == -1,kmp匹配失败,跳过本字节,下字节开始继续匹配;

        //j >= 0,本字节开始匹配,模式串调到j开始

        if (j == -1 || s[i] == p[j])

        {

            i++;

            j++;

        }

        else

        {//从模式串的第几个字节失败则跳到指定位置继续尝试,如在第7字节失败,则跳到第三字节开始(下标为前面子串最大前后匹配长度)

            j = next[j];//ABCDABD    -1 0 0 0 0 1 2;

        }

    }

    if (j == pLen) return i - j;//返回第一个完全匹配位置

    

    return -1;

}

 

 

/*

输出

tmp:A

maxLen:0

tmp:AB

maxLen:0

tmp:ABC

maxLen:0

tmp:ABCD

maxLen:0

tmp:ABCDA

maxLen:1

tmp:ABCDAB

maxLen:2

tmp:ABCDABD

maxLen:0

res :2

*/

int main()

{

    string s = "BBABCDABDKA";

    string p = "ABCDABD";

    int res = KmpSearch(s,p);

    cout << "res :" <<res<<' ';

    return 0;

}

 

 

(2)next数组求取设计

前缀后缀长度求取以及next数组获取:

如果给定的模式串是:“ABCDABD”,从左至右遍历整个模式串,其各个子串的前缀后缀分别如下表格所示:

也就是说,原模式串子串对应的各个前缀后缀的公共元素的最大长度表为:

0 0 0 0 1 2 0;

故对应的next数组为:-1 0 0 0 0 1 2;

(注意:这里的字符串下标是从0开始的,若从1开始,next数组所有元素都对应要加1。)

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值