-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJohoon_No1786.cpp
More file actions
59 lines (43 loc) · 1.02 KB
/
Johoon_No1786.cpp
File metadata and controls
59 lines (43 loc) · 1.02 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
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string T, P;
vector<int> getPi(string pattern) {
int patternSize = pattern.size();
int j = 0;
vector<int> pi(patternSize, 0);
for (int i = 1; i < patternSize; i++) {
while (j > 0 && pattern[i] != pattern[j])
j = pi[j - 1];
if (pattern[i] == pattern[j]) pi[i] = ++j;
}
return pi;
}
vector<int> KMP(string parent, string pattern) {
vector<int> ans;
auto pi = getPi(pattern);
int parentSize = parent.size();
int patternSize = pattern.size();
int j = 0;
for (int i = 0; i < parentSize; i++) {
while (j > 0 && parent[i] != pattern[j])
j = pi[j - 1];
if (parent[i] == pattern[j]) {
if (j == patternSize - 1) {
ans.push_back(i - patternSize + 1);
j = pi[j];
}
else j++;
}
}
return ans;
}
int main() {
getline(cin, T);
getline(cin, P);
auto ans = KMP(T, P);
cout << ans.size() << '\n';
for (int i = 0; i < ans.size(); i++)
cout << ans[i] + 1 << ' ';
}