Skip to content

Commit 85de096

Browse files
committed
3
1 parent ece2d20 commit 85de096

File tree

1 file changed

+25
-41
lines changed

1 file changed

+25
-41
lines changed

ImplementstrStr/ImplementstrStr.cpp

+25-41
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,32 @@
11
class Solution {
22
public:
33
char *strStr(char *haystack, char *needle) {
4-
// Start typing your C/C++ solution below
5-
// DO NOT write int main() function
6-
7-
int hays_length = strlen(haystack);
8-
int needle_length = strlen(needle);
9-
10-
if (hays_length == 0 && needle_length != 0)
11-
return NULL;
12-
if (hays_length == 0 || needle_length == 0)
4+
int n = strlen(haystack);
5+
int m = strlen(needle);
6+
if (m == 0) {
137
return haystack;
14-
15-
int needle_array[needle_length];
16-
17-
getPattern(needle, needle_array, needle_length);
18-
int pos = KMP(haystack, hays_length, needle, needle_array, needle_length);
19-
if (pos != -2)
20-
return haystack + pos + 1;
21-
else
22-
return NULL;
23-
}
24-
25-
int KMP(const char *source, int lens, const char *pattern, const int p[], int lenp) {
26-
int i, j = -1;
27-
for (i = 0; i < lens; i++) {
28-
while (j != -1 && source[i] != pattern[j+1])
29-
j = p[j];
30-
if (source[i] == pattern[j+1])
31-
j += 1;
32-
if (j == lenp - 1) return i - lenp;
338
}
34-
return -2;
35-
}
36-
37-
void getPattern(const char *pattern, int p[], int len) {
38-
p[0] = -1;
39-
int i, j = -1;
40-
for (i = 1; i < len; i++) {
41-
while (j != -1 && pattern[i] != pattern[j+1])
42-
j = p[j];
43-
if (pattern[i] == pattern[j+1])
44-
j += 1;
45-
p[i] = j;
9+
vector<int> next(m, -1);
10+
for (int i = 1, j = -1; i < m; i++) {
11+
while (j != -1 && needle[j+1] != needle[i]) {
12+
j = next[j];
13+
}
14+
if (needle[j+1] == needle[i]) {
15+
j++;
16+
}
17+
next[i] = j;
18+
}
19+
for (int i = 0, j = -1; i < n; i++) {
20+
while (j != -1 && needle[j+1] != haystack[i]) {
21+
j = next[j];
22+
}
23+
if (needle[j+1] == haystack[i]) {
24+
j++;
25+
}
26+
if (j == m - 1) {
27+
return haystack + i - m + 1;
28+
}
4629
}
30+
return NULL;
4731
}
48-
};
32+
};

0 commit comments

Comments
 (0)