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];
}
}
}
};
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]Implement strStr()
- leetcode -- Implement strStr()
- leetcode Implement strStr()
- [leetcode]Implement strStr()
- leetcode(57)- Implement strStr()
- 【leetcode】3.2 Implement strStr()
- LeetCode -- Implement strStr()
- leetcode-28-Implement strStr()
- leetcode-28 Implement strStr()
- leetcode Implement strStr()
- LeetCode (Implement strStr())
- leetcode第15题----- Implement strStr()
- 【LeetCode】Implement strStr()
- [Leetcode]Implement strStr()
- [Leetcode] Implement strStr()
- [LeetCode28] Implement strStr()
- leetcode---Implement strStr()
- leetcode 28: Implement strStr() (KMP算法)
- leetcode-Implement strStr()
- LeetCode(28)Implement Strstr()