Skip to content

Commit 1dfef76

Browse files
authored
Create 3297-count-substrings-that-can-be-rearranged-to-contain-a-string-i.js
1 parent a422d87 commit 1dfef76

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @param {string} word1
3+
* @param {string} word2
4+
* @return {number}
5+
*/
6+
var validSubstringCount = function (word1, word2) {
7+
const mp1 = new Array(26).fill(0)
8+
const mp2 = new Array(26).fill(0)
9+
let missing = 0
10+
11+
for (const c of word2) {
12+
mp1[c.charCodeAt(0) - 'a'.charCodeAt(0)]++
13+
}
14+
15+
for (let i = 0; i < 26; i++) {
16+
if (mp1[i] > 0) {
17+
missing += mp1[i]
18+
}
19+
}
20+
21+
let res = 0
22+
let left = 0
23+
const n = word1.length
24+
25+
for (let right = 0; right < n; right++) {
26+
const c = word1[right].charCodeAt(0) - 'a'.charCodeAt(0)
27+
mp2[c]++
28+
if (mp1[c] > 0 && mp2[c] <= mp1[c]) {
29+
missing--
30+
}
31+
32+
while (missing === 0) {
33+
res += n - right
34+
const left_char = word1[left].charCodeAt(0) - 'a'.charCodeAt(0)
35+
if (mp1[left_char] > 0 && mp2[left_char] <= mp1[left_char]) {
36+
missing++
37+
}
38+
mp2[left_char]--
39+
left++
40+
}
41+
}
42+
43+
return res
44+
}

0 commit comments

Comments
 (0)