//kmp 算法
public class KMP {
public int getMinKmp(String st1, String st2){
if (st2.length() > st1.length()){
return -1;
}
char[] str = st1.toCharArray();
char[] match = st2.toCharArray();
int[] next = getMatchNext(match);
int i = 0,j = 0;//i str指针的位置 j match指针的位置
while (i < str.length && j < match.length){
if (str[i] == match[j]){
i++;
j++;
}else if(next[j] == -1){
i ++;
}else {
j = next[j];
}
}
return j == match.length ? i - j : -1;
}
private int[] getMatchNext(char[] match) {
if (match.length == 1){
return new int[] {-1};
}
int[] next = new int[match.length];
next[0] = -1;
next[1] =0;
int i = 2;
int m = 0;
while (i < match.length){
if (match[i-1] == match[m]){
next[i] = ++m ;
i ++;
}else if (next[m] == -1){
next[i] = 0;
i ++;
}else {
m = next[m];
}
}
return next;
}
public static void main(String[] args) {
KMP kmp = new KMP();
String St1 = "abcabaabaabcacb";
String St2 = "abaabcssjac";
int minKmp = kmp.getMinKmp(St1, St2);
if (minKmp != -1){
System.out.println(St1.substring(minKmp,minKmp + St2.length()).equals(St2) ? true : false);
}
}
}