代码:
package com.wangyq.datastructrue.arithmetic;
import java.util.Arrays;
public class KMP {
public static void main(String[] args) {
String str = "abcabaabaabcacb";
String matchStr = "abaabcac";
int index = kmp(str, matchStr);
System.out.println("字符串所在位置:" + index);
}
private static int kmp(String str, String matchStr) {
char[] strChars = str.toCharArray();
char[] matchChars = matchStr.toCharArray();
//首先建立对应数组
int[] next = getNext(matchStr);
System.out.println("部分匹配数组:" + Arrays.toString(next));
int k = 0;
//循环进行匹配
for (int i = 0; i < strChars.length; i++) {
if (strChars[i] == matchChars[k]) {
k++;
//判断是否匹配成功
if (k == matchChars.length) {
return i - k + 1;
}
} else if (k != 0) {
//匹配失败,重置i和k;
i = i - next[k - 1];
i--;
k = 0;
}
}
return -1;
}
private static int[] getNext(String matchStr) {
char[] matchChars = matchStr.toCharArray();
int[] next = new int[matchChars.length];
int k;
//for循环控制后缀
for (int i = 1; i < matchChars.length; i++) {
//获取前一个元素的值
k = next[i - 1];
if (matchChars[i] == matchChars[k]) {
next[i] = k + 1;
} else {
//重置k
if (matchChars[i] == matchChars[0]) {
next[i] = 1;
} else {
next[i] = 0;
}
}
}
return next;
}
}
运行结果:
部分匹配数组:[0, 0, 1, 1, 2, 0, 1, 0]
字符串所在位置:6