侧边栏壁纸
  • 累计撰写 49 篇文章
  • 累计创建 5 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

KMP

Administrator
2024-08-23 / 0 评论 / 0 点赞 / 13 阅读 / 1539 字
温馨提示:
本文最后更新于 2024-08-23,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

KMP

#include <iostream>
#include <string>
using namespace std;

void getNext(string str, int next[]) {
    int len = str.size();
    next[0] = -1;
    int k = -1;
    int j = 0;
    while (j < len - 1) {
        if (k == -1 || str[j] == str[k]) {
            j++;
            k++;
            next[j] = k;
        }
        else {
            k = next[k];
        }
    }
}

int kmp(string str, string childstr) {
    int l = str.size();
    int ans = -1;
    int i = 0;
    int j = 0;
    int childstrl = childstr.size();

    int next[childstrl] = { 0 };
    getNext(childstr, next);

    while (i < l) {
        if (j == -1 || str[i] == childstr[j]) {
            i++;
            j++;
        }
        else {
            j = next[j];
        }

        if (j == childstrl) {
            ans = i - childstrl;
            break;
        }
    }

    return ans;
}
0

评论区