KMP之计算Next数组

Posted sayiqiu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了KMP之计算Next数组相关的知识,希望对你有一定的参考价值。

KMP的Next数组:模式串的前缀与后缀的“相交”长度

KMP算法步骤:

1.先算next数组

2.若失配(此时模式串下标为j),利用Next数组求出失配后滑动的新位置

  a.Next[j] geq 0,则模式串右移 j-Next[j]

  b.Next[j] = -1,则模式串右移 j+1

 

技术分享图片

 

初始 i = 0, j = -1,Next[ 0 ] = -1(为了后面计算方便);

Step1:

  由于j == -1,i&j++,且Next[i] = j,即Next[1] = 0; 此时 i = 1, j = 0;

  下一个循环:p[ i ] != p[ j ],所以 j = Next[ j ] = Next[ 0 ] = -1,j回退

  j == -1, i&j++,此时 i = 2, j = 0; Next[ i ] = j,即Next [ 2 ] = 0

Step2:

  p [ 2 ] == p [ 0 ] -> i&j++ -> i = 3, j = 1, Next[ 3 ] = 1;

Step3:

  p [ 3 ] == p [ 1 ] -> i&j++ -> i = 4, j = 2, Next[4] = 2;

Step4:

  p [ 4 ] == p [ 2 ] -> i&j++ -> i = 5, j = 3, Next[5] = 3;

Step5:

  p [ 5 ] == p [ 3 ] -> i&j++ -> i = 6, j = 4, Next[6] = 4;

Step6:

  p [ 6 ] != p [ 4 ] -> 失配! -> j = Next[ j ] = Next [ 4 ] = 2

Step7:

  p [ 6 ] != p [ 2 ] -> 失配! -> j = Next[ j ] = Next [2 ] = 0

Step8:

  p [ 6 ] != p [ 0 ] -> 失配! -> j = Next[ j ] = Next [0 ] = -1

Step9:

  j == -1 -> i&j++ -> i = 7, j = 0 -> Next[7] = 0

Step10:

  p [ 7 ] != p [ 0 ] -> 失配! -> j = Next[ j ] = Next [0 ] = -1

Step11:

  i !< strlen(p) -> 循环退出

 

int next[100] = { 0 };

void calNext(char *p, int *next)
{
    next[0] = -1;
    int i = 0, j = -1;
    while (i < strlen(p)) {
        if (j == -1 || p[i] == p[j])    //短路
        {
            i++;
            j++;
            next[i] = j;
        }
        else    //j指针回退过程
            j = next[j];
    }
}

 

以上是关于KMP之计算Next数组的主要内容,如果未能解决你的问题,请参考以下文章

数据结构串---KMP模式匹配算法之获取next数组

KMP算法

KMP算法NEXT数组计算方法

KMP算法NEXT数组计算方法

KMP算法next数组的计算

KMP算法中的next数组如何计算