-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrabin_karp.cpp
More file actions
36 lines (27 loc) · 775 Bytes
/
rabin_karp.cpp
File metadata and controls
36 lines (27 loc) · 775 Bytes
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
#include<bits/stdc++.h>
#include<string.h>
using namespace std;
long long makeHash(string str,int start, int end){
//excluding end
long long ans = 0;
for(int i = start; i < end; i++) ans = ans*33 + (str[i]-'a'+1);
return ans;
}
int main(){
string text;
string patt ;
cout << "Enter text" << endl;
cin >> text;
cout << "Enter pattern to search" << endl;
cin >> patt;
long long hash_patt = makeHash(patt, 0, patt.size());
int i;
for(i = 0; i < text.size(); i++){
long long temp = makeHash(text, i, i+patt.size());
if(temp == hash_patt){
cout << "match found at position: " << i << endl;
break;
}
}
if(i == text.size()) cout << "Pattern not found" << endl;
}