forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rabin_Karp_Algorithm_using_prefix_sum.cpp
123 lines (100 loc) · 1.78 KB
/
Rabin_Karp_Algorithm_using_prefix_sum.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/*
Rabin Karp Algorithm (using prefix sum)
=========================================
Given a text and a pattern, find all the occurences of the pattern in the text
Time Complexity: O(n) n=size of string
Space Complexity: O(1)
*/
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 1e9 + 7;
const int p = 31;
// returns (a^b)%mod
int powr(int a, int b) {
int ans = 1;
while (b) {
if (b & 1LL) {
ans *= a;
ans %= mod;
}
a *= a;
b = b >> 1;
a %= mod;
}
return ans % mod;
}
// returns (a^-1)%mod
int inv(int a) {
return powr(a, mod - 2) % mod;
}
// Assigns hash to a string
int polyHashString(string s) {
int hash = 0;
int coef = 1;
for (int i = 0; i < s.size(); i++) {
hash += (s[i] - 'a' + 1) * coef;
coef *= p;
coef %= mod;
hash %= mod;
}
return hash % mod;
}
// Rabin Karp Algorithm for pattern matching
// returns indices of pattern in string s
void rabinKarp(string s, string pat) {
int pat_hash = polyHashString(pat);
int n = s.size(), m = pat.size();
int pref[n] = {0};
for (int i = 0; i < n; i++) {
pref[i] = (s[i] - 'a' + 1) * powr(p, i);
pref[i] %= mod;
}
for (int i = 1; i < n; i++) {
pref[i] += pref[i - 1];
pref[i] %= mod;
}
bool patFound = 0;
for (int i = 0; i <= (n - m); i++) {
// substring from s[l.......r]
// r = i+m - 1
int l = i;
int r = i + m - 1;
int new_hash = pref[r];
if (i - 1 >= 0) {
new_hash -= pref[l - 1];
}
new_hash += mod; new_hash %= mod;
if (new_hash == (pat_hash * powr(p, l)) % mod) {
cout << i << endl;
patFound = 1;
}
}
if (!patFound) {
cout << "Not found";
}
}
// Driver Code
signed main() {
// Take input
string s, pat;
cin >> s >> pat;
rabinKarp(s, pat);
}
/*
Input:
ilovecoding
love
Output:
1
Input:
aaaaaaaa
aaa
Output:
0
1
2
3
4
5
*/