6 next数组示例与代码

        A  B  C  A  A  C  B  B  C  B  A  D  A  A  B  C  A  C  B  D

原始   0  0  0  0   1  1  0  0  0   0  0  1  0   1  1  2  3  4   0  0

优化  -1  0  0 -1  1  1  0  0  0   0  -1 1 -1   1  0  0 -1 4   0  0

Java代码:

public static int[] next(char[] t){

  int [] next = new int[t.length];

  next[0]=-1;

  int i=0,j=-1;

  while(i<t.length-1){

    if(j==-1||t[i]==t[j]){

      i++;

      j++;

      if(t[i]!=t[j])

        next[i]=j;

      esle 

        next[i]=next[j];

    }

  }

  return next;  

}

原文地址:https://www.cnblogs.com/JaneSJ/p/5915200.html