-
Notifications
You must be signed in to change notification settings - Fork 28
/
Implement_strStr().cpp
61 lines (57 loc) · 1.61 KB
/
Implement_strStr().cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
// naive O(m * (n - m + 1))
int strStr(char *haystack, char *needle) {
int n = strlen(haystack); //1
int m = strlen(needle); //1
// if(m == 0) return 0;
for(int i = 0, j; i <= n - m; ++i) {
bool flag = true;
for(j = 0; j < m; ++j) {
if(haystack[i + j] != needle[j]) {
flag = false;
break;
}
}
if(flag) return i;
}
return -1;
}
// KMP O(m)
int strStr(string haystack, string needle) {
int n = haystack.length();
int m = needle.length();
if(m > n) return -1;
if(m == 0 and n == 0) return 0;
int LPS[m + 1];
int len = 0;
LPS[0] = 0;
for(int i = 1; i < m; ) {
if(needle[i] == needle[len]) {
LPS[i++] = ++len;
} else {
if(len == 0) {
LPS[i++] = 0;
} else {
len = LPS[len - 1];
}
}
}
for(int i = 0, j = 0; i < n; ) {
if(needle[j] == haystack[i]) {
j++, i++;
}
if(j == m) {
// found first occurance
return i - j;
} else if(needle[j] != haystack[i]) {
if(j == 0) {
i++;
} else {
j = LPS[j - 1];
}
}
}
return -1;
}
};