代码中有注解—不对的地方请指出共同学习
package com.test.autimatic;
public class GpKmp {
public static void main(String[] args) {
System.out.println(kmp("abbabbabab","abbaba"));
}
public final static int kmp(String source,String target){
if(source == null || target == null || source.length() < target.length()){
return -1;
}
int s = 0;
int t = 0;
int[] arrayKmp = getArrayKmp(target);
for (; s < source.length() && t < target.length();) {
String sStr = source.substring(s, s + 1);
String tStr = target.substring(t, t + 1);
if(sStr.equals(tStr)){
t++;s++;
}else if(arrayKmp[t] == -1){
s++;
}else{
t = arrayKmp[t];
}
}
return t == target.length() ? s - target.length() : -1;
}
private static final int[] getArrayKmp(String target){
int[] kmp = new int[target.length()];
kmp[0] = -1;kmp[1] = 0;int index = 0;
for (int i = 2; i < target.length(); i++) {
index = kmp[i - 1];
while (kmp[index] != -1 && !target.substring(index,index + 1).equals(target.substring(i - 1,i))){
index = kmp[index];
}
if(target.substring(index,index + 1).equals(target.substring(i - 1,i))){
kmp[i] = index + 1;
}
}
return kmp;
}
}