Skip to content

Commit 701cc69

Browse files
3306_Count_of_Substrings_containing_every_single_vowel_and_k_consoneants_II.java
1 parent bf4cabf commit 701cc69

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Problem Number 3306
2+
3+
// Count of Substrings containing every single vowel and K consonants II
4+
5+
class Solution {
6+
public long countOfSubstrings(String word, int k) {
7+
return substringsWithAtMost(word, k) - substringsWithAtMost(word, k - 1);
8+
}
9+
10+
private long substringsWithAtMost(String word, int k) {
11+
if (k == -1)
12+
return 0;
13+
14+
long res = 0;
15+
int vowels = 0;
16+
int uniqueVowels = 0;
17+
Map<Character, Integer> vowelLastSeen = new HashMap<>();
18+
19+
for (int l = 0, r = 0; r < word.length(); ++r) {
20+
if (isVowel(word.charAt(r))) {
21+
++vowels;
22+
if (!vowelLastSeen.containsKey(word.charAt(r)) || vowelLastSeen.get(word.charAt(r)) < l)
23+
++uniqueVowels;
24+
vowelLastSeen.put(word.charAt(r), r);
25+
}
26+
while (r - l + 1 - vowels > k) {
27+
if (isVowel(word.charAt(l))) {
28+
--vowels;
29+
if (vowelLastSeen.get(word.charAt(l)) == l)
30+
--uniqueVowels;
31+
}
32+
++l;
33+
}
34+
if (uniqueVowels == 5) {
35+
final int minVowelLastSeen = Arrays.asList('a', 'e', 'i', 'o', 'u')
36+
.stream()
37+
.mapToInt(vowel -> vowelLastSeen.get(vowel))
38+
.min()
39+
.getAsInt();
40+
res += minVowelLastSeen - l + 1;
41+
}
42+
}
43+
44+
return res;
45+
}
46+
47+
private boolean isVowel(char c) {
48+
return "aeiou".indexOf(c) != -1;
49+
}
50+
}

0 commit comments

Comments
 (0)