
原题链接
- 使用KMP算法实现 strStr()
- 关于kmp算法,首先定义了next数组,next数组就是一个前缀表
- 首先定义了getNext 函数来 生成要检测字符串的next数组
- 然后在主函数中进行调用,关于前缀表的使用:每当检测到两个字符不同的时候,就将needle的索引定位到next[j - 1]的位置,然后继续来判断执行,直到 needl 中的下标 为 needle的长度的时候,就停止。
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
int[] next = new int[needle.length()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && needle.charAt(j) != haystack.charAt(i))
j = next[j - 1];
if (needle.charAt(j) == haystack.charAt(i))
j++;
if (j == needle.length())
return i - needle.length() + 1;
}
return -1;
}
private void getNext(int[] next, String s) {
int j = 0;
next[0] = 0;
for (int i = 1; i < s.length(); i++) {
while (j > 0 && s.charAt(j) != s.charAt(i))
j = next[j - 1];
if (s.charAt(j) == s.charAt(i))
j++;
next[i] = j;
}
}
}