class Solution {
public int strStr(String haystack, String needle) {
int[]next;
int n = haystack.length();
int m = needle.length();
if (m == 0) {
return 0;
}
if (n == 0||n < m) {
return -1;
}
next = getNext(needle);
int i = 0, j = 0;
while (i < n && j < m) {
if (j == -1||haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
}else{
j = next[j];
if (n - i + 1 < m - j + 1) {
break;
}
}
}
return j == m ? i - m : -1;
}
public int[] getNext(String pattern){
int j = 0, k = -1;
int[]next = new int[pattern.length()];
next[0] = -1;
while(j < pattern.length()-1){
if (k == -1 || pattern.charAt(k) == pattern.charAt(j)) {
j++;
k++;
if (pattern.charAt(k) == pattern.charAt(j)) {
next[j] = next[k];
}else
next[j] = k;
}
else
k = next[k];
}
return next;
}
}