Doubt in an implementation of Rabin-Karp Algorithm

Правка en1, от Yashraj1402, 2023-06-29 15:06:56

I have a doubt about the implementation of the Rabin-Karp Algorithm given on CP Algorithms.com

Problem: Given two strings — a pattern s  and a text t, determine if the pattern appears in the text and if it does, enumerate all its occurrences in O(|s| + |t|) time.

Solution:

vector<int> rabin_karp(string const& s, string const& t) {
    const int p = 31; 
    const int m = 1e9 + 9;
    int S = s.size(), T = t.size();

    vector<long long> p_pow(max(S, T)); 
    p_pow[0] = 1; 
    for (int i = 1; i < (int)p_pow.size(); i++) 
        p_pow[i] = (p_pow[i-1] * p) % m;

    vector<long long> h(T + 1, 0); 
    for (int i = 0; i < T; i++)
        h[i+1] = (h[i] + (t[i] - 'a' + 1) * p_pow[i]) % m; 
    long long h_s = 0; 
    for (int i = 0; i < S; i++) 
        h_s = (h_s + (s[i] - 'a' + 1) * p_pow[i]) % m; 

    vector<int> occurences;
    for (int i = 0; i + S - 1 < T; i++) { 
        long long cur_h = (h[i+S] + m - h[i]) % m; 
        if (cur_h == h_s * p_pow[i] % m)
            occurences.push_back(i);
    }
    return occurences;
}

In the last comparison:

if (cur_h == h_s * p_pow[i] % m)
            occurences.push_back(i);

Why do we need to multiply h_s by p_pow[i], shouldn't it be just if(cur_h == h_s)

Please help.

Теги #rabin-karp

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский Yashraj1402 2023-06-29 15:06:56 1367 Initial revision (published)