KMP模式匹配算法

#include <iostream>
#include <string>
int next[255];
void getnext(const std::string &str)
{
    int i = 0;
    int j = -1;
    next[0] = -1;
    while (i < str.size())
    {
        if (j == -1 || str[i] == str[j])
        {
            ++i;
            ++j;
            if (str[i] == str[j])
            {
                next[i] = next[j];
            }
            else
            {
                next[i] = j;
            }
        }
        else
        {   
            j = next[j];
        }
    }
}

int IndexKMP(const std::string &str, const std::string& test_str)
{
    getnext(test_str);

    int index = -1;
    int i = 0;
    int j = 0;
    
    while (i < (int)str.size() && j < (int)test_str.size())
    {
        if (j == -1 || str[i] == test_str[j])
        {
            ++i;
            ++j;
        }
        else
        {
            j = next[j];
        }
    }
    
    if (j >= (int)test_str.size())
    {
        index = i - test_str.size();
    }

    return index;
}

int main()
{
    std::string str("abcdabdcabaaabaace");
    std::string test("abaac");
    int index = IndexKMP(str, test);
    std::cout << index << std::endl;
    return 0;
}

在这里插入图片描述
有符号数与无符号数比较的坑:
有符号与无符号比较:有符号数会转换成无符号数来进行比较(如int 与 unsigned int 比较,int 转换成 unsigned int)。
有符号与非无符号数比较:非无符号转化成有符号(如int 与 unsigned char比较,unsigned char 转换成 int)。
无符号与非有符号数比较:非有符号转化成有符号(如unsigned int 与 char比较,char 转换成 unsigned int)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值