Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
题目的要求就是实现KMP算法
public class Solution {
public String strStr(String haystack, String needle) {
//if(haystack.equals("") && needle.equals("")) return "";
if(needle.equals("")) return haystack;
String ans = null;
int i = 0, j = 0;
int next[] = getNext(needle);
while(i < haystack.length() && j < needle.length()){
if(j == -1 || haystack.charAt(i) == needle.charAt(j)){
++j; ++i;
}else{
j = next[j];
}
}
if(j != 0 && j == needle.length()){
ans = new String(haystack.toCharArray(), i - j, haystack.length() - i + j );
}
return ans;
}
private int[] getNext(String str){
if(str.length() > 0){
int[] next = new int[str.length()];
next[0] = -1;
int len = str.length() - 1;
int i = 0, k = -1;
while(i < len){
if(k == -1 || str.charAt(i) == str.charAt(k)){
++i; ++k;
next[i] = k;
}else{
k = next[k];
}
}
return next;
}
return null;
}
}