forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement_strStr.cc
42 lines (42 loc) · 1.13 KB
/
Implement_strStr.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public:
void init(int *p, char *needle, int len) {
p[0] = -1;
int j = -1;
for (int i = 1; i < len; i++) {
while (j > -1 && needle[i] != needle[j + 1]) {
j = p[j];
}
if (needle[j + 1] == needle[i]) {
j++;
}
p[i] = j;
}
}
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = strlen(needle);
if (len == 0) {
return haystack;
}
int *p = new int[len];
init(p, needle, len);
int i = 0, j = -1;
while (haystack[i] != '\0') {
while (j > -1 && haystack[i] != needle[j + 1]) {
j = p[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
if (j == len - 1) {
delete []p;
return haystack + i - len + 1;
}
i++;
}
delete []p;
return NULL;
}
};