class Solution {
public int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
int[] pi = new int[m];
//kmp中j是共同前缀的长度
for(int i = 1, j = 0; i < m; i ++){
while(j > 0 && needle.charAt(i) != needle.charAt(j)){
j = pi[j - 1];
}
if(needle.charAt(i) == needle.charAt(j)){
j ++;
}
pi[i] = j;
}
for(int i = 0, j = 0; i < n; i ++){
while(j > 0 && haystack.charAt(i) != needle.charAt(j)){
j = pi[j - 1];
}
if(haystack.charAt(i) == needle.charAt(j)){
j ++;
}
if(j == m){
return i - m + 1;
}
}
return -1;
}
}
11-03
3万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-09
536
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)