@@ -4,7 +4,41 @@ using namespace std;
44
55class Solution {
66public:
7- int strStr (string haystack, string needle) {
8- return haystack.find (needle);
9- }
7+
8+ // Rabin-Karp Algorithm for string matching
9+ int strStr (string haystack, string needle) {
10+ long long mod = 1e9 + 7 , p = 53 ;
11+ int h = haystack.size (), n = needle.size ();
12+ if (h < n) return -1 ;
13+ if (n == 0 ) return 0 ;
14+
15+ // precalculating powers of p
16+ vector<long long > p_pow (max (h, n));
17+ p_pow[0 ] = 1 ;
18+ for (int i = 1 ; i < p_pow.size (); i++) {
19+ p_pow[i] = (p_pow[i - 1 ] * p) % mod;
20+ }
21+ // calculating haystack_hash
22+ vector<long long > haystack_hash (haystack.size () + 1 , 0 );
23+ for (int i = 0 ; i < h; i++) {
24+ haystack_hash[i + 1 ] = (haystack_hash[i] + (haystack[i] - ' a' + 1 ) * p_pow[i]) % mod;
25+ }
26+
27+ // calculating needle_hash
28+ long long needle_hash = 0 ;
29+ for (int i = 0 ; i < n; i++) {
30+ needle_hash = (needle_hash + (needle[i] - ' a' + 1 ) * p_pow[i]) % mod;
31+ }
32+
33+ // checking for matching hashes
34+ for (int i = 0 ; i <= h - n; i++) {
35+ long long curr_hash = (haystack_hash[i + n] + mod - haystack_hash[i]) % mod;
36+ if (curr_hash == (needle_hash * p_pow[i]) % mod) {
37+ return i;
38+ }
39+ }
40+
41+ // if no hash is find
42+ return -1 ;
43+ }
1044};
0 commit comments