Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

rabin karp algorithm

// Rabin Karp Alogorithm - (search substring)

#include <iostream>
#include <string>

using namespace std;

#define ll long long
#define BASE 227
#define MOD 1000000007

ll hhash(string s, ll l = -1) {
	if (l == -1)
		l = s.size();
    ll h = 0;
	for (ll i = 0; i < l; i++)
    	h = (h * BASE + s[i]) % MOD;
    return h;
}

ll rabin_karp(string s, string t) {
    ll h1 = hhash(t), h2 = hhash(s, t.size());

    if (h1 == h2)
    	return 0;

    ll power = 1;
    for (ll i = 0; i < t.size(); i++)
    	power = (power * BASE) % MOD;

   	for (ll i = t.size(); i < s.size(); i++) {
   		h2 = (h2*BASE + s[i]) % MOD;
        h2 = (h2 - (power * s[i-t.size()] % MOD) + MOD) % MOD;
    	if (h1 == h2)
        	return i - (t.size() - 1);
   	}

   	return -1;
}

int main() {
	string s, t;
    cin>>s>>t;

    ll ans = rabin_karp(s, t);
    if(ans == -1)
    	cout<<"String not found"<<endl;
    else
    	cout<<"String ""<<t<<"" found at position "<<ans<<endl;

   return 0;
}

//Time Complexity: O(n)
//Space Complexity: O(n)
Comment

rabin-karp algorithm

1 function RabinKarp(string s[1..n], string pattern[1..m])
2     hpattern := hash(pattern[1..m]);
3     for i from 1 to n-m+1
4         hs := hash(s[i..i+m-1])
5         if hs = hpattern
6             if s[i..i+m-1] = pattern[1..m]
7                 return i
8     return not found
Comment

PREVIOUS NEXT
Code Example
Python :: derivative of multivariable function pytorch 
Python :: access dynamicall to name attribute python 
Python :: RuntimeError: cannot open featureclass in python 
Python :: flatten a list of lists python 
Python :: how to update pip in python 
Shell :: remove steam from ubuntu 
Shell :: lumen run command 
Shell :: how to check mongodb status in ubuntu 
Shell :: git store credential 
Shell :: remove all docker iamges commandl 
Shell :: Unit mongodb.service could not be found ubuntu 
Shell :: debian disable ipv6 
Shell :: delete all zone identifier files 
Shell :: how to install yum in ubuntu 
Shell :: remove unused packages ubuntu 
Shell :: restart redis ubuntu 
Shell :: remote origin already exists 
Shell :: ubuntu tweak 
Shell :: install wps ubuntu 
Shell :: install maven in ubuntu 
Shell :: find the parent branch of a git branch 
Shell :: uninstall apache2 ubuntu 20.04 
Shell :: git set url with token 
Shell :: apple m1 pod install issue 
Shell :: uninstall opencv on anaconda ubuntu 
Shell :: how to install yup 
Shell :: ubuntu install imagemagick 
Shell :: uninstall webpack globally 
Shell :: check firewall centos 7 
Shell :: docker: Error response from daemon: dial unix docker.raw.sock: connect: no such file or directory 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =