[LeetCode] Find Substring With Given Hash Value

2156. Find Substring With Given Hash Value

The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:

  • hash(s, p, m) = (val(s[0]) p0 + val(s[1]) p1 + … + val(s[k-1]) * pk-1) mod m.
    Where val(s[i]) represents the index of s[i] in the alphabet from val(‘a’) = 1 to val(‘z’) = 26.

You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue.

The test cases will be generated such that an answer always exists.

A substring is a contiguous non-empty sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string subStrHash(string s, int power, int modulo, int k, int hashValue) {
long hash = 0, p = power, pos = 0;

for(int i = s.length() - 1; i >= 0; --i) {
hash = (hash * power + s[i] - 'a' + 1) % modulo;
if(i <= s.length() - k) {
if(i < s.length() - k) hash = (hash + modulo - (((s[i + k] - 'a' + 1) * p) % modulo)) % modulo;
if(hash == hashValue) pos = i;
} else {
p = (p * power) % modulo;
}
}

return s.substr(pos, k);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/30/PS/LeetCode/find-substring-with-given-hash-value/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.