-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement-strStr.cpp
52 lines (48 loc) · 1017 Bytes
/
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
#include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
void getNext(string needle, int next[])
{
int i = 0, k = -1;
next[0] = -1;
while (i < needle.size())
{
if (k == -1 || needle[i] == needle[k])
{
next[++i] = ++k;
}
else
k = next[k];
};
return;
}
int strStr(string haystack, string needle)
{
const int len = needle.length();
int next[len + 1];
getNext(needle, next);
int i = 0, k = 0;
while (i < haystack.length() && k < len)
{
if (k == -1 || haystack[i] == needle[k])
{
i++, k++;
}
else
k = next[k];
};
if (k == needle.length())
return i - k;
else
return -1;
}
};
int main()
{
Solution S;
cout << S.strStr("sshsefsds", "sefs");
return 0;
}