Question
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Code
public int strStr(String haystack, String needle) {
if (haystack.equals(needle) || needle.length() == 0) {
return 0;
}
if (haystack.length() < needle.length()) {
return -1;
}
int[] next = getNext(needle);
int j = 0, i = 0;
while (i < haystack.length() && j < needle.length()) {
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
if (next[j] == -1) {
i++;
j = 0;
} else {
j = next[j];
}
}
if (j == needle.length()) {
return i - j;
}
}
return -1;
}
public int[] getNext(String needle) {
int[] next = new int[needle.length()];
int k = -1, i = 0;
next[0] = -1;
while (i < needle.length() - 1) {
if (k == -1 || needle.charAt(i) == needle.charAt(k)) {
i++;
k++;
next[i] = k;
} else {
k = next[k];
}
}
return next;
}