KMP算法思想的学习,是参考的博客http://kb.cnblogs.com/page/176818/。
真正具体实现的时候,会发现代码思想 与算法过程有些偏颇(当然这是很正常的),贴上代码供以后参考。
public class ImplementStrStr {
public int strStr(String haystack, String needle) {
if(needle.length() == 0) return 0;
int[] next = next(needle);
int i = 0, j = 0;
while(i < haystack.length() && j < needle.length()) {
if(j == -1 || haystack.charAt(i) == needle.charAt(j)) {
++i;
++j;
}
else
j = next[j]; //不匹配时,需要将待匹配子串的指针j移动到相应位置(该位置由next()函数提供)
}
return j >= needle.length() ? i - needle.length() : -1;
}
// next函数,求子串指针j的移动位置
public int[] next(String needle) {
int len = needle.length();
int[] next = new int[len];
int i = 0, j = -1;
next[0] = -1;
while(i < len - 1) {
if(j == -1 || needle.charAt(i) == needle.charAt(j)) {
++i;
++j;
next[i] = (needle.charAt(i) == needle.charAt(j) ? next[j] : j);
}
else
j = next[j];
}
return next;
}
}
同时,这也是LeetCode题目Implement StrStr() 的解。
在我看完链接博客所述的算法思想后,以为代码中实现的也会是对指针i的移动,却没想是j的变化。
KMP算法复杂度为O(m+n).