Блог пользователя gautam94

Автор gautam94, 12 лет назад, По-английски

I was reading about hashing from here and I am unable to understand the part about calculation of hash of a substring. I am calculating the hash of the entire input string in this way : h (S) = S [0] + S [1] * P + S [2] * P ^ 2 + S [3] * P ^ 3 + ... + S [N] * P ^ N

Suppose P = 31 and a = 1, b = 2, c = 3 and so on. Then for the input string abcdab, h[0] = 1, h[1] = 32, h[2] = 2915, h[3] = 122079, h[4] = 1045600, h[5] = 58303902. Now from these values, how can I calculate h[0..1] or h[3..5]?

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
12 лет назад, скрыть # |
Rev. 3  
Проголосовать: нравится +6 Проголосовать: не нравится

Let's store suffix hashes instead.

We can now calculate hashes like that: h[i] = h[i + 1] * p + s[i]

So, we want to find h[l..r]. Let len = r - l + 1

Let's write h[l] and h[r + 1]:

h[l] = s[l] * p^0 + s[l + 1] * p^1 + s[l + 2] * p^2 + ... + s[r] * p^(len - 1) + s[r + 1] * p^len + ...
h[r + 1] = s[r + 1] * p^0 + s[r + 2] * p^1 + ...
h[r + 1] * p^len = s[r + l] * p^len + s[r + 2] * p^(len+1) + ...
h[l] - h[r + 1] * p^len = s[l] * p^0 + s[l + 1] * p^1 + s[l + 2] * p^2 + ... + s[r] * p^(len - 1)

That's exactly what we need.