我自己的java的实现代码
public static int kmp(char[] primary,char[] model,int position) {
int i = position, j = 0;
int[] next = next(model);
if (i < primary.length && j < model.length) {
if (primary[i] == model[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == model.length) return i - j;
else return 0;
}
public static int[] pmt(char[] model) {
int[] next = new int[model.length];
next[0] = 0;
int maxPosition = 0;
for (int index = 1; index < next.length; index++) {
maxPosition = next[index - 1];
while (maxPosition > 0 && model[maxPosition] != model[index]) {
maxPosition = next[maxPosition];
}
if (model[maxPosition] == model[index]) next[index] = maxPosition;
else next[index] = 0;
}
return next;
}
public static int[] next(char[] model) {
int[] next = new int[model.length];
next[0] = -1;
int max = -1, index = 0;
while (index < model.length - 1) {
if (max == -1 || model[index] == model[max]) {
max++;
next[++index] = max;
} else {
max = next[max];
}
}
return next;
}
public static int[] nextval(char[] model) {
int[] nextval = new int[model.length];
nextval[0] = -1;
int max = -1, index = 0;
while (index < model.length - 1) {
if (max == -1 || model[index] == model[max]) {
max++;
index++;
if (model[index] == model[max]) {
nextval[index] = nextval[max];
} else {
nextval[index] = max;
}
} else {
max = nextval[max];
}
}
return nextval;
}