这次的KMP算法还是很有难度的, 我搞懂了next数组的创建, 但是没有搞懂是如何匹配的, 所以今天就先了解下, 之后再回头来看
关键点就是: 找到最长相等前后缀
构造next数组三步:
初始化: 定义两个指针i和j,j指向前缀末尾位置,i指向后缀末尾位置(next数组下标)
前后缀不相等的情况: 不相等的话就向前回退 j = next[j - 1]
前后缀相等的情况: 如果相等了就j++
class Solution {
public void getNext(int[] next, String s){
int j = 0;
next[0] = j;
//遍历数组来对ij匹配, 这里的i是j后面一个
for (int i = 1; i<s.length(); i++){
//判断不相等的情况
while(j>=0 && s.charAt(i) != s.charAt(j)){
j=next[j - 1];
}
//相等的话就j++
if(s.charAt(i)==s.charAt(j)){
j++;
}
next[i] = j;
}
}
下面的匹配部分没有很理解, 直接上代码算了
(注意:这里的i和j有点不同)
public int strStr(String haystack, String needle) {
if(needle.length()==0){
return 0;
}
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-needle.length()+1);
}
}
return -1;
}
}