Skip to content

Commit d238c5b

Browse files
authored
Create 2156-find-substring-with-given-hash-value.js
1 parent b463e80 commit d238c5b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} power
4+
* @param {number} modulo
5+
* @param {number} k
6+
* @param {number} hashValue
7+
* @return {string}
8+
*/
9+
var subStrHash = function (s, power, modulo, k, hashValue) {
10+
let n = s.length;
11+
const p_pow = Array(n + 1);
12+
p_pow[0] = 1n;
13+
power = BigInt(power);
14+
let m = BigInt(modulo);
15+
for (let i = 1; i < p_pow.length; i++) p_pow[i] = (p_pow[i - 1] * power) % m;
16+
17+
const val = (ch) => BigInt(ch.charCodeAt(0) - "a".charCodeAt(0));
18+
const h = Array(n + 1).fill(0n);
19+
for (let i = n - 1; i >= 0; i--)
20+
h[i] = (h[i + 1] * power + val(s[i]) + 1n) % m;
21+
22+
for (let i = 0; i + k - 1 < n; i++) {
23+
let cur_h = (h[i] - h[i + k] * p_pow[k]) % m;
24+
let temp = (cur_h + m) % m;
25+
if (temp == hashValue) {
26+
return s.substr(i, k);
27+
}
28+
}
29+
return "";
30+
};

0 commit comments

Comments
 (0)