zoukankan      html  css  js  c++  java
  • 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];
        }
    }
  • 相关阅读:
    改变Ecplise项目窗口字体样式
    反射笔记
    日期、时间戳、字符串之间的转换
    Ajax处理后台返回的Json数据
    Ajax动态切换按钮
    生成随机数验证码
    Apache-SimpleEmail 简单应用
    Apache-POI 简单应用
    JavaMail API的应用
    checkbox怎么判断是否选中
  • 原文地址:https://www.cnblogs.com/sayiqiu/p/10127944.html
Copyright © 2011-2022 走看看