为什么需要KMP
解决字符串朴素模式匹配速度过慢的问题。朴素模式匹配相当于一种暴力匹配算法。
next数组
next数组用来干嘛?
next数组是要拿过来计算子串的匹配位置的,解决朴素模式匹配的遍历多余次数问题。
next数组的值 -1 代表的就是当前j位置的字符往前,有多少重复的字符
next数组的算法
1.首位一定是0
2.当j开始移动时,看j之前的字符串中是否有出现重复的前缀和后缀
如果有,k = 重复的字符串长度 + 1
*重复的字符串包括p1p2p3 = p2p3p4
,但不包括这种情况p1p2p3p4 = p1p2p3p4
(即全部相等)
3.没有相同前后缀取1
算例:
代码
public int[] next(String needle) {
int[] next = new int[needle.length()];
next[1] = 0;
int i = 1, j = 0;
while (i < needle.length()-1) {
if (j == 0 || needle.charAt(i) == needle.charAt(j)) {
next[++i] = ++j;
}
else {
j = next[j];
}
}
return next;
}
//测试:
String next = " ababaaaba";
System.out.println(Arrays.toString(test.next(next)));