子串查找kmp算法 C++实现

9 篇文章 0 订阅
7 篇文章 0 订阅

本文章为代替git保存代码

Kmp算主要分为两步:
(1)取得next数组
(2)查找子串

代码如下:

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

bool get_next(const std::string& str, std::vector<int>& next) {
    if (str.empty()) {
        return false;
    }

    next.resize(str.size());

    // str[0 ~ k-1] = str[p-k ~ p-1]
    // 0       k-1 k         p-k       p-1  p
    // a b c d e   f  g h    a   b c d e    n  o p q t s t u v w x y z
    int k = -1;
    int p = 0;
    next[0] = -1;
    while (p + 1 < str.size()) {
        if (k == -1 || str[k] == str[p]) {
            k++;
            p++;
            next[p] = k;
        } else {
            k = next[k];
        }
    }
    return true;
}

void next_test() {
    std::vector<int> next;
    std::string sub_str = "abaabcaba";
    assert(get_next(sub_str, next));
    for (auto index = next.begin(); index != next.end(); ++index) {
        std::cout << *index << std::endl;
    }
}

int kmp(const std::string& str, const std::string& sub) {
    std::vector<int> next;

    if (sub.empty() && str.empty()) {
        return 0;
    }

    if (sub.size() > str.size()) {
        return -1;
    }

    if (!get_next(sub, next)) {
        return -1;
    }

    for (auto index = next.begin(); index != next.end(); ++index) {
        std::cout << *index << std::endl;
    }

    int ret = -1;

    int i = 0;
    int j = 0;

    int str_len = str.size();
    int sub_len = sub.size();

    // 直接在while循环中使用str.size(),会出现有符号数到无符号数的转化 
    while (i < str_len && j < sub_len) {
        if (j == -1 || str[i] == sub[j]) {
            ++i;
            ++j;
        } else {
            j = next[j];
        }
    }

    if (j == sub.size()) {
        ret = i - sub.size();
    }

    return ret;
}

int main(int argc, char** argv) {
    //next_test();

    std::string str = "sbxajcbbdsccshdcbusdcbjhcbuvbdfb";
    std::string sub = "cbbd";

    auto ret = kmp(str, sub);

    std::cout << "str = " << str << std::endl;
    std::cout << "sub = " << sub << std::endl;
    std::cout << "pos = " << ret << std::endl;

    return 0;
}

另外一种比较容易理解的KMP获取next数组的实现方式:

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


void GetNext(std::vector<int>& next, const std::string& str) {
    if (str.length() == 0) {
        return;
    }
    next[0] = -1;
    for (int i = 1; i < str.length(); ++i) {
        int nextindex = i - 1;
        while (nextindex >= 0) {
            if (next[nextindex] == -1) {
                next[i] = 0;
                break;
            } else if (str[next[nextindex] + 1] == str[i]) {
                next[i] = next[nextindex] + 1;
                break;
            } else {
                nextindex = next[nextindex-1];
            }
        }
    }
}

int main(int argc, char** argv) {
    std::string str = "abcdabc";
    std::vector<int> next;
    next.resize(str.length());
    GetNext(next, str);

    for (size_t i = 0; i < next.size(); ++i) {
        std::cout << next[i] << std::endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值