跳到正文

算法·理论

一种极致简化、好写好记的 1-index KMP 写法

AeeE5x约 1 分钟
原文
文章信息与版本

文章信息

发布
2026年10月23日
收录
2026年10月24日
更新
2026年11月9日
篇幅
约 1 分钟

版本

  1. v1当前

提供一种极致简化好写好记的 1-index KMP 写法。

C++
int a[2000010], nxt[2000010];
void KMP(int n){
    nxt[0] = -1;
    for(int i = 1; i <= n; i ++){
        nxt[i] = i;
        do nxt[i] = nxt[nxt[i] - 1] + 1;
        while(nxt[i] && a[i] != a[nxt[i]]);
    }
}

nxti←i\mathrm{nxt}_i\gets i 的目的只是为了下面的循环能在第一轮恰好用 nxti−1+1\mathrm{nxt}_{i - 1} + 1 作为初始值。

nxti\mathrm{nxt}_i 在每一轮表示的是待匹配的字符的位置,因为是 1-index,所以 border 长度恰好就是要匹配的字符的下标。

若失配,将上一轮匹配失败带来的 +1+1 去掉,取下一个 border。

考虑边界,显然我们对于 i≥1i \ge 1 有 nxti+1>0\mathrm{nxt}_i+1 > 0,因此循环条件不会触发 nxti≠0\mathrm{nxt}_i\ne 0。

边界就是 nxti−1\mathrm{nxt}_i - 1 在上一轮取到 00,下一轮 nxti←nxt0+1=0\mathrm{nxt}_i\gets \mathrm{nxt}_0+1=0,这种情况不需要继续匹配,直接退出即可。

原文
存档评论15 条抓取于