Skip to content

Commit 4399d7f

Browse files
authored
Update 2851-string-transformation.js
1 parent 35937bc commit 4399d7f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

2851-string-transformation.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,70 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} t
4+
* @param {number} k
5+
* @return {number}
6+
*/
7+
const numberOfWays = function (s, t, k) {
8+
const n = s.length,
9+
M = 1e9 + 7
10+
const pos = kmp(s + s.slice(0, n-1), t)
11+
const fk = [0, 0]
12+
calcFK()
13+
14+
let res = 0
15+
for (let p of pos) {
16+
if (p === 0) res = (res + fk[0]) % M
17+
else res = (res + fk[1]) % M
18+
}
19+
return res
20+
21+
function kmp(s, t) {
22+
const m = s.length,
23+
n = t.length
24+
const pi = new Array(n).fill(0)
25+
for (let i = 1; i < n; ++i) {
26+
let j = pi[i - 1]
27+
while (j > 0 && t.charAt(j) !== t.charAt(i)) j = pi[j - 1]
28+
if (j === 0 && t.charAt(0) !== t.charAt(i)) pi[i] = 0
29+
else pi[i] = j + 1
30+
}
31+
let j = 0
32+
const res = []
33+
for (let i = 0; i < m; ++i) {
34+
while (j >= n || (j > 0 && s.charAt(i) !== t.charAt(j))) j = pi[j - 1]
35+
if (s.charAt(i) === t.charAt(j)) j++
36+
if (j === n) res.push(i - n + 1)
37+
}
38+
return res
39+
}
40+
41+
function calcFK() {
42+
fk[1] =
43+
(((powWrap(n - 1, k, M) + BigInt(((k % 2) * 2 - 1)) + BigInt(M)) % BigInt(M)) * powWrap(n, M - 2, M)) % BigInt(M)
44+
fk[0] = (fk[1] - BigInt(((k % 2) * 2 - 1)) + BigInt(M)) % BigInt(M)
45+
// console.log(fk)
46+
fk[1] = Number(fk[1])
47+
fk[0] = Number(fk[0])
48+
}
49+
50+
function powWrap(a,b,M) {
51+
a = BigInt(a)
52+
b = BigInt(b)
53+
M = BigInt(M)
54+
return pow(a,b,M)
55+
}
56+
57+
function pow(a, b, M) {
58+
if (b === 0n) return 1n
59+
if ((b & 1n) === 0n) return pow((a * a) % M, b >> 1n, M)
60+
return (a * pow((a * a) % M, b >> 1n, M)) % M
61+
}
62+
}
63+
64+
65+
// another
66+
67+
168
class Modulo {
269
/**
370
* @param {number} modulo

0 commit comments

Comments
 (0)