i       0    1    2    3    4    5    6    7    8 

     s     a    b    a    b    a    a    b    a    b 

next[i]  -1    0    0    1    2    3    1    2    3 

先计算前缀next[i]的值: 

next[i]的值主要是看s[i]之前的字符串中重复的子串长度。next[0] = -1,定值。   

next[1]是看s[1]之前的字符串“a”中重复的子串长度为0,故next[1] = 0。 

next[2]是看s[2]之前的字符串“ab”中重复的子串长度为0,故next[2] = 0。 

next[3]是看s[3]之前的字符串"aba"中重复的子串长度,s[0]与s[2]重复,长度为1,故next[3] = 1。 

next[4]是看s[4]之前的字符串"abab"中重复的子串长度,s[01]与s[23]重复,长度为2,故next[4] = 2。 

next[5]是看s[5]之前的字符串"ababa"中重复的子串长度,s[012]与s[234]重复,长度为3,故next[5] = 3。 

next[6]是看s[6]之前的字符串"ababaa"中重复的子串长度,s[0]与s[5]重复(因为多了一个a,无法找到长度为3的重复字符串,这只能是s[0]和s[5]重复),长度为1,故next[6] = 1。 

同样的,求next[7]和next[8]分别为2和3。 

接下来计算nextval[i]的值: 

nextval[i]的求解需要比较s中next[i]所在位置的字符是否与s[i]的字符一致,如果一致则用s[next[i]]的nextval的值作为nextval[i],如果不一致,则用next[i]做为nextval[i]。 

nextval[0] = -1,和next[0]的值一样。 

nextval[1],比较s[next[1]] ?= s[1],next[1] = 0,s[0] = a,而s[1] = b,二者不一致,则nextval[1] = next[1] = 0。 

nextval[2],比较s[next[2]] ?= s[2],next[2] = 0,s[0] = a,而s[2] = a,二者一致,则nextval[2] = nextval[s[next[2]]] = nextval[s[0]] = -1(严谨来看这么表述是有问题的,因为nextval[2]表示nextval数组中 第3个数值,而nextval[s[0]]表示的是s[0]对应的字母‘a’所对应的nextval值 -1,这里nextval[]的用法并不严谨,只是为了表述方便 )。  

nextval[3],比较s[next[3]] ?= s[3],next[3] = 1,s[1] = b,而s[3] = b,二者一致,则nextval[3] = nextval[s[next[3]]] = nextval[s[1]] = 0。 

nextval[4],比较s[next[4]] ?= s[4],next[4] = 2,s[2] = a,而s[4] = a,二者一致,则nextval[4] = nextval[s[next[4]]] = nextval[s[2]] = -1。 

nextval[5],比较s[next[5]] ?= s[5],next[5] = 3,s[3] = b,而s[5] = a,二者不一致,则nextval[5] = next[5] = 3。 

同样的求nextval[6],nextval[7],nextval[8]分别为 0 ,-1 , 0。 

这里是nextval的下标从-1开始,如果从1开始,则其余各位均+1,nextval为0,1,0,1,0,4,1,0,1 



ref: http://www.slyar.com/blog/kmp-next-nextval.html 

i    0  1  2  3  4  5  6  7  8 

s    a  b  a  b  a  a  b  a  b 

next  -1  0  0  1  2  3  1  2  3 


nextval[0] = -1; 

s[1]=b != s[next[1]]=s[0]=a; nextval[1]=next[1]=0; 

s[2]=a = s[next[2]]=s[0]=a, nextval[2]=nextval[0]=-1; 

s[3]=b = s[next[3]]=s[1]=b, nextval[3]=nextval[1]0; 

s[4]=a = s[next[4]]=s[2]=a, nextval[4]=nextval[2]=-1; 

s[5]=a != s[next[5]]=s[3]=b, nextval[5]=next[5]=3; 

s[6]=b = s[next[6]]=s[1]=b, nextval[6]=nextval[1]=0; 

s[7]=a = s[next[7]]=s[2]=a, nextval[7]=nextval[2]=-1; 

s[8]=b = s[next[8]]=s[3]=b, nextval[8]=nextval[3]=0; 

nextval -1 0 -1 0 -1 3 0 -1 0 
有的时候下标从1开始即 0 1 0 1 0 4 1 0 1 

posted on 2017-08-01 20:27  王小东大将军  阅读(534)  评论(0编辑  收藏  举报