【KMP算法】知识点讲解+模板

老生常谈的算法了...记得也是前前后后看了好多次,但是不久后就又忘记next数组的含义。

这次我觉得终于能一句话看懂了,不需要我再像以前看图解一样把自己绕晕:



模板(带我自己写的注释):

void getnext() {
    next[1] = 0;               //这里默认字符串都从下标1开始哈!
    for(int i = 2; i <= n; i++) {  //i从2开始
        int j = next[i - 1];   
        while(t[j + 1] != t[i] && j > 0) {
            j = next[j];
        }
        if(t[j + 1] == t[i]) {
            next[i] = j + 1;
        } else {
            next[i] = 0;
        }
    }
}
int kmp() {
    int j = 0;
    for(int i = 1; i <= m; i++){
        while(t[j + 1] != s[i] && j > 0) {   //如果不匹配则一直去赋为next[j]直到匹配或无法匹配
            j = next[j];
        }
        if(t[j + 1] == s[i]) {
            j++;
        }
        if(j >= n) {
            return i - n + 1;    //第一个匹配的起点
        }
    }
    return 0;
}

反正赛前你就背吧,背得滴水不漏。

猜你喜欢

转载自blog.csdn.net/m0_38033475/article/details/80281903