-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathImplement strStr().cpp
More file actions
41 lines (37 loc) · 934 Bytes
/
Implement strStr().cpp
File metadata and controls
41 lines (37 loc) · 934 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
36
37
38
39
40
41
class Solution
{
public:
char *strStr(char *haystack, char *needle)
{
if (*needle == 0)
{
return haystack;
}
int hlen = strlen(haystack);
int nlen = strlen(needle);
vector<int> next(nlen + 1);
next[1] = next[0] = 0;
int k = 0;
for (int i = 2; i <= nlen; ++i)
{
for (; k != 0 && needle[k] != needle[i-1]; k = next[k])
nullptr;
if (needle[k] == needle[i-1])
k++;
next[i] = k;
}
int hi = 0, ni = 0;
while (hi < hlen)
{
for (ni = next[ni]; ni < nlen && needle[ni] == haystack[hi]; ni++, hi++)
nullptr;
if (ni == 0)
hi++;
else if (ni == nlen)
{
return haystack + hi - nlen;
}
}
return nullptr;
}
};