代码随想录算法训练营第九天| 28. 实现 strStr() 和讲讲KMP
**28. 实现 strStr() **
https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/

public void getNext(int[] next,String s){
int j = -1;
next[0] = j;
for (int i = 1; i < s.length(); i++) {
while (j >= 0 && s.charAt(i) != s.charAt(j+1)){
j = next[j];
}
if (s.charAt(i) == s.charAt(j+1)){
j++;
}
next[i] = j;
}
}
public int strStr(String haystack, String needle) {
int[] next = new int[needle.length()];
getNext(next,needle);
int j = -1;
for (int i = 0; i < haystack.length(); i++) {
while (j >= 0 && haystack.charAt(i) != needle.charAt(j+1)){
j = next[j];
}
if (haystack.charAt(i) == needle.charAt(j+1)){
j++;
}
if (j == needle.length() - 1){
return i - j;
}
}
return -1;
}
总结:KMP 没什么好说的
讲讲KMP


总结:见到KMP的题就构造next数组再用next数组
构造的流程分别是:
1、初始化(j自己定义,i走for循环,i从1开始,j从-1开始)。
2、while判断前后缀不同时,向前回退。
3、if判断前后缀相同时j++
4、无论如何都要来一次next[i] = j。
用的流程是:
1、初始化j去遍历B串,i走for循环(i从0开始,j从-1开始)。
2、while判断不同时,j往前回退。
3、if判断相同时,j++。
4、if判断j走到B串的最后一位了,就说明在A中找到B了,这时按需返回相应的值或者执行相应的操作即可。
浙公网安备 33010602011771号