// if failed, return 0intIndex(char[] T,char[] S,int pos){// T is mode string, S is to be matched, pos is the started positionint i = pos, j =1;while( i <= S[0]&& j <= T[0])// length of string in first element of char array{if(S[i]==T[j]){
i++;j++;}else{
i = i - j +2;
j =1;}}if(j > T[0])return i-T[0];return0;}
KMP算法和简单算法的差别在于 i 不再回溯,而 j 也不每次都变为1,会根据next函数来回溯。给定next值后KMP算法如下:
// if failed, return 0intIndex(char[] T,int next[],char[] S,int pos){// T is mode string, S is to be matched, pos is the started positionint i = pos, j =1;while( i <= S[0]&& j <= T[0])// length of string in first element of char array{if(j==0|| S[i]==T[j]){
i++;
j++;}else{
j = next[j];}}if(j > T[0])return i-T[0];return0;}
而 next 值的计算方法其实就是对模式串自身进行串匹配
voidget_next(char[] T,int next[]){int i =1, j =0;// different1 : j = 0 not 1
next[1]=0;// initwhile( i < T[0])// different2 : not <= but <{if(j==0|| T[i]==T[j]){
i++;
j++;
next[i]=j;//different3 : record next[] here}else{
j = next[j];}}return;}