Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这题虽然用朴素字符串匹配算法也能过,但是最好还是用KMP算法,毕竟笔试面试的时候可没有这么简单。
KMP算法的精髓在于求出next数组,next数组记录的是模式串匹配失效后主串应该和模式串的哪一位进行比较:比如在模式串第j位匹配失效,那么下一步主串当前位应该和模式串第next[j]位相比较,如果再失效,则继续和模式串next[next[j]]位相比较。
KMP算法的时间复杂度为O(m+n),空间复杂度为O(m).
下面是java实现,需牢记。
public class Solution {
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0)
return 0;
int[] next = getNext(needle);
for(int i = 0,j = -1; i < haystack.length() ; i ++){
while(j > -1 && 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;
}
public int[] getNext(String str){
if(str ==null || str.length() == 0)
return null;
int[] next = new int[str.length() + 1];
for(int i = 0 , j = -1 ; i < str.length() ; i ++){
if(i == 0 ){
next[i] = j;
continue;
}
while(j > -1 && str.charAt(j) != str.charAt(i)){
j = next[j];
}
if(str.charAt(i) == str.charAt(j + 1)) {
j++;
}
next[i] = j;
}
return next;
}
}