Rabin-Karp Pattern Matching

parent 1adfaf21
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAXN 100100
#define BASE 256
#define MOD 1000000007LL
using namespace std;
typedef long long ll;
char T[ MAXN + 1 ], P[ MAXN + 1 ];
int hashing() {
int n = strlen( T ), k = strlen( P );
ll hash = 0LL, rhash = 0LL;
for( int i = 0; i < k; i++ ) {
hash = hash * BASE % MOD;
hash = ( hash + P[ i ] ) % MOD;
rhash = ( rhash * BASE + T[ i ] ) % MOD;
}
if( rhash == hash ) return 0;
ll po = 1LL;
for( int i = 0; i < k - 1; i++ ) {
po = po * BASE % MOD;
}
for( int i = 1; i < n - k + 1; i++ ) {
rhash = ( rhash - po * T[ i - 1 ] );
if( rhash < 0 ) rhash += MOD;
rhash = rhash * BASE % MOD;
rhash = ( rhash + T[ i + k - 1 ] ) % MOD;
if( rhash == hash ) return i;
}
return -1;
}
int main( void ) {
scanf("%s%s", T, P );
int val = hashing();
if( val == -1 ) {
printf("Not found!\n");
} else {
printf("First occurence found in pos: %d\n", val );
}
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment