Count Vowel Substrings of a String LeetCode solution in C++

1
class Solution {
2
public:
3
bool isVowel(char c) {
4
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
5
};
6

7
int atMostK(string &s, int k) {
8
int res = 0, i = 0, n = s.size();
9
unordered_map<char, int> mp;
10

11
for (int j = 0; j < n; j++) {
12
if (!isVowel(s[j])) {
13
i = j + 1;
14
// Clear map as new substring will begin
15
mp.clear();
16
continue;
17
}
18
mp[s[j]]++;
19
while (mp.size() > k) {
20
mp[s[i]]--;
21
if (mp[s[i]] == 0) mp.erase(s[i]);
22
i++;
23
}
24
res += j - i + 1;
25
}
26
return res;
27
}
28

29
int countVowelSubstrings(string str) {
30
return atMostK(str, 5) - atMostK(str, 4);
31
}
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0