您的位置:首页 > 其它

LeetCode Implement strStr()

2014-08-13 21:05 302 查看
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];
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode kmp