The j=next[j] understanding of the next array in the KMP algorithm

This article was written on oneNote. My brother doesn't know how to convert oneNote to md, so I can only take screenshots in a stupid way. . . If you think it's too hard to read, you can ask me for the original

Contact Email: [email protected]

figure 1

—————————– Figure 1 Figure 2 dividing line ———————————————–

figure 2

————— Figure 2 and Figure 3 dividing line (remember to align with the above picture..) —————————

image 3

Also:
Attach my KMP algorithm (C language version)

void get_next(int **next,HString S){            //next数组:其值为S的每一位所拥有相同的最大子串长度。子串的范围为0到该位的长度-10表示没有相同的子串,1表示最大子串为1。。依次类推;下标0没有子串,设置为特殊位-1
        int i,j;
        (*next) = (int *)malloc(sizeof(int)*S->size);
        (*next)[0] = -1;
        i = 0;  //i表示两个含义:S的游标和next的游标
        j = 0;  //j表示next[i]的值
        while(i < S -> size){
                if(j == -1 || S -> Base[i] == S -> Base[j]){
                        ++i;
                        ++j;
                        (*next)[i] = j;
                }else{
                        //j--;  //j--是否也可以?  2018-4-21:从实验结果来说没问题,可是从理解上来说就不对了。
                        j = (*next)[j];
                }
        }
}

int Index_KMP(HString S,HString T,int pos){
        int i,j,*next;          //KMP的next数组 
        if(pos + T -> size > S -> size +1 ) return -1;
        get_next(&next,T);
        i = j = 0;
        while(i < S -> size && j < T -> size){
                if(j == -1 || S -> Base[i] == T -> Base[j]){
                        i++;
                        j++;
                }else{
                        j = next[j];
                }
        }
        if(j >= T -> size) return i - T -> size+1;
        return -1;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324599715&siteId=291194637