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