KMP算法-在文本串中查找模式串的起始位置

#include <iostream>
#include <vector>
#include <string>

//构建部分匹配表

std::vector<int> build_next(const std::string& patt) {
    std::vector<int> next{ 0 };
    int prefix_len = 0;
    int i = 1;
    while (i < patt.size()) {
        if (patt[prefix_len] == patt[i]) {
            prefix_len++;
            next.push_back(prefix_len);
            i++;
        }
        else {
            if (prefix_len == 0) {
                next.push_back(0);
                i++;
            }
            else {
                prefix_len = next[prefix_len - 1];
            }
        }
    }
    return next;
}

int kmp_search(const std::string& string, const std::string& patt) {
    std::vector<int> next = build_next(patt);
    int i = 0;  // 主串中的指针
    int j = 0;  // 子串中的指针
    while (i < string.size()) {
        if (string[i] == patt[j]) {  // 字符匹配,指针后移
            i++;
            j++;
        }
        else if (j > 0) {  // 字符失配,根据next跳过子串前面的一些字符
            j = next[j - 1];
        }
        else {  // 子串第一个字符就失配
            i++;
        }
        if (j == patt.size()) {  // 匹配成功
            return i - j;
        }
    }
    return -1;  // 匹配失败
}

int main() {
    std::string string = "ababcabcacbab";
    std::string patt = "abcac";
    int index = kmp_search(string, patt);
    if (index != -1) {
        std::cout << "Pattern found at index " << index << std::endl;
    }
    else {
        std::cout << "Pattern not found" << std::endl;
    }
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值