Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
就是 KMP 了
class Solution {
public:
char *strStr(char *haystack, char *needle) {
int i = 0, j = 0;
int hlen = strlen(haystack);
int nlen = strlen(needle);
int *next = new int[nlen];
GetNext(needle, next);
while (i < hlen && j < nlen) {
if (j == -1 || haystack[i] == needle[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j == nlen)
return haystack + i - j;
else
return NULL;
}
void GetNext(char *needle, int *next) {
int nlen = strlen(needle);
int j = 0;
int k = -1;
next[0] = -1;
while (j < nlen - 1) {
if (k == -1 || needle[j] == needle[k]) {
k++;
j++;
next[j] = k;
}
else {
k = next[k];
}
}
}
};