-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathKMP.cpp
72 lines (64 loc) · 1.24 KB
/
KMP.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)
void KMP() {
string str, pat;
cin >> str >> pat;
int n = str.size();
int m = pat.size();
vector<ll> lps(m, 0);
int len = 0;
int i = 1;
while(i < m) {
if(pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
} else {
if(len) {
len = lps[len - 1];
} else {
i++;
}
}
}
i = 0;
int j = 0;
vector<int> ans;
while(i < n) {
if(str[i] == pat[j]) {
i++;
j++;
if(j == m) {
ans.pb(i - m + 1);
j = lps[j - 1];
}
} else {
if(j) {
j = lps[j - 1];
} else {
i++;
}
}
}
if(ans.empty()) {
cout << "Not Found\n";
} else {
cout << ans.size() << endl;
for(int i : ans) {
cout << i << " ";
}
cout << endl;
}
cout << endl;
}
int main() {
fastio;
int t;
cin >> t;
while(t--) {
KMP();
}
}