-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path28.cpp
More file actions
35 lines (32 loc) · 661 Bytes
/
28.cpp
File metadata and controls
35 lines (32 loc) · 661 Bytes
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
class Solution {
public:
void getNext(string p, vector<int> &next) {
next[0] = 0;
int j = 0;
for (int i = 1; i < p.length(); i++) {
while (j > 0 && p[i] != p[j])
j = next[j - 1];
if (p[i] == p[j])
++j;
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.length() == 0) return 0;
vector<int> next(needle.length());
getNext(needle, next);
int j = 0;
int pos = -1;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && needle[j] != haystack[i])
j = next[j - 1];
if (needle[j] == haystack[i])
++j;
if (j == needle.length()) {
pos = i - needle.length() + 1;
break;
}
}
return pos;
}
};