-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnuthMorrisPratt.cpp
More file actions
66 lines (57 loc) · 1.26 KB
/
Copy pathKnuthMorrisPratt.cpp
File metadata and controls
66 lines (57 loc) · 1.26 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
60
61
62
63
64
65
66
/**
* Author: Kevin Li
* Lang: C++
* Description: classic KMP String search
*/
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
#define pb push_back
struct kmp {
string s;
int *p;
vector<int> indices;
kmp () {}
kmp (string _s) : s(_s) {}
void process() {
p = new int[s.length()];
int i = 0, j = -1; p[0] = -1;
for (int i = 1; i < s.length(); i++) p[i] = 0;
while (i < s.length()) {
while (j >= 0 && s[i] != s[j]) {
j = p[j];
}
i++; j++;
p[i] = j;
}
}
void search(string S) {
while (!indices.empty()) indices.pop_back();
int i = 0, j = 0;
while (i < S.length()) {
while (j >= 0 && S[i] != s[j]) {
j = p[j];
}
i++; j++;
if (j == s.length()) {
indices.pb(i-j);
j = p[j];
}
}
}
void print() {
for (int i = 0; i < indices.size(); i++) {
cout << indices[i] << " ";
}
cout << endl;
}
};
string s, S;
int main() {
cin >> s >> S;
kmp KMP = kmp(s);
KMP.process();
KMP.search(S);
KMP.print();
}