Skip to content

Commit 71a7a4d

Browse files
Merge pull request codemistic#466 from Aman5989/patch-14
create find-substring-with-given-hash-value.cpp
2 parents 9aab194 + d86c259 commit 71a7a4d

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public:
3+
string subStrHash(string s, int p, int mod, int k, int target) {
4+
long h = 0, N = s.size(), pp = 1; // `pp` = p^k
5+
vector<long> hash(N);
6+
string r(rbegin(s), rend(s));
7+
for (int i = 0; i < N; ++i) {
8+
if (i < k) pp = pp * p % mod;
9+
h = (h * p + (r[i] - 'a' + 1)) % mod; // push r[i] into the window
10+
if (i - k >= 0) { // pop r[i-k] out of the window
11+
h = (h - (r[i - k] - 'a' + 1) * pp % mod + mod) % mod;
12+
}
13+
if (i >= k - 1) hash[i] = h;
14+
}
15+
reverse(begin(hash), end(hash));
16+
for (int i = 0; i < N; ++i) {
17+
if (hash[i] == target) return s.substr(i, k); // hash[i] is the hash of `s[i .. (i+k-1)]`
18+
}
19+
return "";
20+
}
21+
};

0 commit comments

Comments
 (0)