字符串匹配算法

本文详细介绍了KMP算法中的next数组构造方法,包括前缀表统一减一和直接使用前缀表两种方式,并提供了相关函数get_next和get_str的实现。建议优先选择直接使用前缀表的方法,以提高理解性。
摘要由CSDN通过智能技术生成

KMP

1、构造next数组

next 数组是前缀表或者说是前缀表的变形,前缀表记录的是最长相同的前后缀的长度。
举个例子:aabaaf——>[0, 1, 0, 1, 2, 0]

常用的两种next数组

1、前缀表统一减一
  1. abaaf——>[0, 1, 0, 1, 2, 0]——>[-1, 0, -1, 0, 1, -1 ]
  2. 使用j = next[j]回退
  3. 代码
void get_next(int *next, const string &s) 
{
    int j = -1;
    next[0] = j;
    for (int i = 1; i < s.size(); i++) {
        while (j >= 0 && s[i] != s[j+1]) {
            j = next[j];
        }
        if (s[i] == s[j+1]) {
            j++;
        }
        next[i] = j;
    }
}

int get_str(string haystack, string needle)
{
    if (needle.size() == 0) {
        return 0;
    }
    int next[needle.size()];
    get_next(next, needle);
    int j = -1;
    for (int i = 0; i < haystack.size(); i++) {
        while (j >=0 && haystack[i] != needle[j+1]) {
            j = next[j];
        }
        if (haystack[i] == needle[j+1]) {
            j++;
        }
        if (j == needle.size() -1) {
            return (i - needle.size() +1)
        }
    }
    return -1;
}
2、直接使用前缀表
  1. aabaaf——>[0, 1, 0, 1, 2, 0]
  2. 使用j = next[j-1]回退
  3. 代码
void get_next(int *next, const string &s) 
{
    int j = 0;
    next[0] = 0;
    for (int i = 1; i < s.size(); i++) {
        while (j > 0 && s[i] != s[j]) {
            j = next[j-1];
        }
        if (s[i] == s[j]) {
            j++;
        }
        next[i] = j;
    }
}

int get_str(string haystack, string needle)
{
    if (needle.size() == 0) {
        return 0;
    }
    int next[needle.size()];
    get_next(next, needle);
    int j = 0;
    for (int i = 0; i < haystack.size(); i++) {
        while (j >0 && haystack[i] != needle[j]) {
            j = next[j-1];
        }
        if (haystack[i] == needle[j]) {
            j++;
        }
        if (j == needle.size()) {
            return (i - needle.size() +1)
        }
    }
    return -1;
}
建议

建议使用前缀表直接作为next数组,比较好理解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值