next数组求解
public int[] makeNext(char[] arr) {
int[] next = new int[arr.length];
next[0] = -1;
int k = -1, j = 0;
while (j < arr.length - 1){
// k 前缀 j后缀
if (k == -1 || arr[j] == arr[k]) {
if (arr[j+1] == arr[k+1]){
next[++j] = next[++k];
} else{
next[++j] = ++k;
}
} else {
k = next[k];
}
}
return next;
}
求
next数组
的过程可以认为是将模式串拆分成n个子串,分别对每个子串求前缀和后缀的最长公共匹配字符数
l
public int match(String haystack, String needle) {
char[] arr = needle.toCharArray();
int[] next = makeNext(arr);
for (int i = 0, j = 0; i < haystack.length();){
if (j == -1 || haystack.charAt(i) == arr[j]){
i++;j++;
if (j == arr.length) return i - arr.length;
} else {
j = next[j];
}
}
return -1;
}