Search
 
SCRIPT & CODE EXAMPLE
 

CPP

string search c++

// 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

PREVIOUS NEXT
Code Example
Cpp :: c++ contains 
Cpp :: how to compare two char* in c++ 
Cpp :: c++ capture screen as pixel array 
Cpp :: cpp class constructor 
Cpp :: what is g++ and gcc 
Cpp :: tree to array c++ 
Cpp :: how to make Dijkstra in c++ 
Cpp :: sort vector c++ 
Cpp :: how to slice vector in c++ 
Cpp :: c++ compile to exe command line 
Cpp :: c++ output current timestamp 
Cpp :: C++ Increment and Decrement 
Cpp :: c++ Least prime factor of numbers till n 
Cpp :: c++ loop through list 
Cpp :: create matrix cpp 
Cpp :: c++ region 
Cpp :: C++ Integer Input/Output 
Cpp :: c++ function of find maximum value in an array 
Cpp :: passing custom function in sort cpp 
Cpp :: cpp execute command 
Cpp :: sfml keyboard events cpp 
Cpp :: C++ fibo 
Cpp :: resharper fold if statement 
Cpp :: full implementation of binary search tree in C++ 
Cpp :: ue4 int to enum c++ 
Cpp :: Array declaration by specifying the size in C++ 
Cpp :: has substr c++ 
Cpp :: How to pass a multidimensional array to a function in C and C++ 
Cpp :: oop in c++ have 5 
Cpp :: c++ else if 
ADD CONTENT
Topic
Content
Source link
Name
2+1 =