Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c30c8cf

Browse files
authored
Create 3306-count-of-substrings-containing-every-vowel-and-k-consonants-ii.js
Solved count-of-substrings-containing-every-vowel-and-k-consonants-ii
1 parent 822c53a commit c30c8cf

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* Sliding Window
3+
* Time O(n) | Space O(1)
4+
* https://leetcode.com/problems/count-of-substrings-containing-every-vowel-and-k-consonants-ii/
5+
* @param {string} word
6+
* @param {number} k
7+
* @return {number}
8+
*/
9+
var countOfSubstrings = function(word, k) {
10+
11+
const countSubStrWithAtLeastKConsonent = (k) => {
12+
13+
let left = 0;
14+
let right = 0;
15+
const vowels = new Set(["a", "e", "i", "o", "u"]);
16+
let vowelsCount = {};
17+
let consonentCount = 0;
18+
let count = 0;
19+
20+
while (right < word.length) {
21+
22+
const letter = word[right];
23+
24+
if (vowels.has(letter)) {
25+
vowelsCount[letter] = (vowelsCount[letter] && vowelsCount[letter] + 1) || 1;
26+
}
27+
if (!vowels.has(letter)) {
28+
consonentCount++;
29+
}
30+
31+
while (Object.keys(vowelsCount).length === 5 && consonentCount >= k) {
32+
count += word.length - right;
33+
34+
if (vowels.has(word[left])) {
35+
vowelsCount[word[left]] -= 1;
36+
if (vowelsCount[word[left]] === 0) {
37+
delete vowelsCount[word[left]];
38+
}
39+
}
40+
41+
if (!vowels.has(word[left])) {
42+
consonentCount -= 1;
43+
}
44+
45+
left++;
46+
}
47+
48+
right++;
49+
}
50+
51+
return count;
52+
}
53+
54+
55+
return countSubStrWithAtLeastKConsonent(k) - countSubStrWithAtLeastKConsonent(k+1);
56+
};

0 commit comments

Comments
 (0)