class Solution {
/**
KMP算法,模式串匹配,构建next数组,不用每次都返回起点开始比较,原O(m*n),KMP O(m+n)
*/
public int strStr(String haystack, String needle) {
int nh = haystack.length();
int nn = needle.length();
if(nn == 0) return 0;
// 构建next数组
int[] next = new int[nn];
for(int i = 1,j = 0;i < nn;i++){
// 不等的回溯
while(j > 0 && needle.charAt(i) != needle.charAt(j)){
// 为什么回溯j-1呢?因为j这个点已经不相等了,通过next[j]回溯都是相等的,所以看前边有没有相等的,没有就再往前,直到为0
j = next[j-1];
}
// 如果相等就同步++,此处j++就行了,i在for循环会自增
if(needle.charAt(i) == needle.charAt(j)) j++;
// 最后j回溯到哪个位置,就赋值
next[i] = j;
}
// 开始匹配
for(int i = 0,j = 0;i < nh;i++){
while(j > 0 && needle.charAt(j) != haystack.charAt(i)){
j = next[j-1];
}
if(needle.charAt(j) == haystack.charAt(i)) j++;
// 如果模式串到结尾了,表示能完全匹配,返回开始索引
if(j == nn){
return i - nn + 1;
}
}
return -1;
}
}
KMP算法
最新推荐文章于 2025-05-21 12:04:25 发布