码迷,mamicode.com
首页 > 编程语言 > 详细

KMP之计算Next数组

时间:2018-12-16 21:45:07      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:退出   src   code   分享   计算   指针   http   分享图片   strlen   

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数组

标签:退出   src   code   分享   计算   指针   http   分享图片   strlen   

原文地址:https://www.cnblogs.com/sayiqiu/p/10127944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!