-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path18.RabinKarp.cpp
59 lines (43 loc) · 1.07 KB
/
18.RabinKarp.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
/*
* This program searches for a pattern in a text using
* Rabin - Karp Algorithm
*
* Coded by: Abdurrezak Efe
*
* */
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int prime = 7;
int pattern_hash;
vector<int> indexes;
int hasher(string s)
{
int result = 0;
for(int i=0;i<s.size();i++)
result += (s[i] - 'a' + 1)*pow(prime, s.size()-i-1);
return result;
}
void rabin_karp(string text, string pattern)
{
int m = pattern.size();
int cur_hash = hasher(text.substr(0,m));
//cout << cur_hash << endl;
for(int i=0; i < text.size()-m+1; i++) //searching
{
if(cur_hash == pattern_hash)
if(text.substr(i,m) == pattern)
indexes.push_back(i);
cur_hash = prime*(cur_hash - (text[i]-'a'+1)*pow(prime, m-1))+(text[i+m]-'a'+1); //updating hash in O(1)
}
}
int main()
{
string text, pattern;
cin >> text >> pattern;
pattern_hash = hasher(pattern);
rabin_karp(text, pattern);
for(int i=0;i<indexes.size();i++)
cout << indexes[i] << endl;
}