-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28.cpp
More file actions
48 lines (43 loc) · 1.06 KB
/
28.cpp
File metadata and controls
48 lines (43 loc) · 1.06 KB
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
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
vector<int> next = getNext(needle);
int j = 0;
for (int i = 0; i < haystack.size(); ++i) {
while (j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if (haystack[i] == needle[j]) {
++j;
}
if (j == needle.size()) {
return i - j + 1;
}
}
return -1;
}
private:
vector<int> getNext(const string& s) {
vector<int> pi(s.size(), 0);
for (int i = 1; i < s.size(); ++i) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j]) {
j = pi[j - 1];
}
if (s[i] == s[j]) {
++j;
}
pi[i] = j;
}
return pi;
}
};
int main()
{
Solution s;
std::cout << s.strStr("ababe", "ab") << std::endl;;
std::cout << s.strStr("ababe", "eb") << std::endl;;
}