package com.it.alg.kmp;
import java.util.Arrays;
import java.util.stream.Collectors;
public class NextTest {
public static void main(String[] args) {
String s = "aaab";
System.out.println(s);
System.out.println(Arrays.stream(next(s)).boxed().collect(Collectors.toList()));
System.out.println(Arrays.stream(nextVal(s)).boxed().collect(Collectors.toList()));
System.out.println(kmp(s, "b"));
}
public static int[] next(String sub) {
int[] next = new int[sub.length()];
char[] chars = sub.toCharArray();
int i = 0, j = -1;
next[0] = -1;
while (i < chars.length - 1) {
if (j == -1 || chars[i] == chars[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
for (int item = 0; item < next.length; item++) {
next[item]++;
}
return next;
}
public static int[] nextVal(String sub) {
int[] nextVal = new int[sub.length()];
char[] chars = sub.toCharArray();
int i = 0, j = -1;
nextVal[0] = -1;
while (i < chars.length - 1) {
if (j == -1 || chars[i] == chars[j]) {
if (chars[++i] != chars[++j]) {
nextVal[i] = j;
} else {
nextVal[i] = nextVal[j];
}
} else {
j = nextVal[j];
}
}
for (int item = 0; item < nextVal.length; item++) {
nextVal[item]++;
}
return nextVal;
}
public static int kmp(String str, String sub) {
char[] strChars = str.toCharArray();
char[] subChars = sub.toCharArray();
int[] nextVal = nextVal(sub);
int i = 1, j = 1;
while (i <= str.length() && j <= sub.length()) {
if (j == 0 || strChars[i - 1] == subChars[j - 1]) {
i++;
j++;
} else {
j = nextVal[j - 1];
}
}
if (j > sub.length()) return i - sub.length() - 1;
return -1;
}
}
运行结果: