-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRabin-karp-algorithm.cpp
More file actions
46 lines (46 loc) · 1.07 KB
/
Rabin-karp-algorithm.cpp
File metadata and controls
46 lines (46 loc) · 1.07 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
void check_pattern() {
int mod = 1e9 + 7;
int z = 127;
string a, b;
cin >> a >> b;
int n = (int)a.size();
int m = (int)b.size();
auto check = [&] (int st, int en) -> bool{
int p = 0;
for (int i = st; i <= en; ++i) {
if (a[i] != b[p]) return 0;
p++;
}
return 1;
};
int64_t val = 0, curr_val = 0;
vector<int> ans;
for (int i = 0; i < min(n,m); ++i) {
int x = b[i] - '0' + 1;
val = (val + x * power_mod(z, m - i - 1, mod)) % mod;
int y = a[i] - '0' + 1;
curr_val = (curr_val + y * power_mod(z, m - i - 1, mod)) % mod;
if (i == m - 1 && curr_val == val && check(0, m - 1)) {
ans.push_back(1);
}
}
for (int i = m; i < n; ++i) {
int x = a[i] - '0' + 1;
int y = a[i - m] - '0' + 1;
int val_z = (y * power_mod(z, m - 1, mod)) % mod;
curr_val = (((curr_val - val_z + mod) % mod * z) + x) % mod;
if (curr_val == val && check(i - m + 1, i)) {
ans.push_back(i - m + 2);
}
}
int k = (int)ans.size();
if (k > 0) {
cout << k << "\n";
for (int i = 0; i < k; ++i) {
cout << ans[i] << " ";
}
}else {
cout << "Not Found";
}
cout << "\n\n";
}