改进的模式匹配算法——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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值