forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-vowel-substrings-of-a-string.cpp
67 lines (60 loc) · 1.7 KB
/
count-vowel-substrings-of-a-string.cpp
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
57
58
59
60
61
62
63
64
65
66
67
// Time: O(n)
// Space: O(1)
class Solution {
public:
int countVowelSubstrings(string word) {
static const int k = 5;
return atLeastK(word, k);
}
private:
int atLeastK(const string& word, int k) {
static const unordered_set<int> VOWELS = {'a', 'e', 'i', 'o', 'u'};
unordered_map<int, int> cnt;
int result = 0;
for (int i = 0, left = 0, right = 0; i < size(word); ++i) {
if (!VOWELS.count(word[i])) {
cnt.clear();
left = right = i + 1;
continue;
}
++cnt[word[i]];
for (; size(cnt) > k - 1; ++right) {
if (!--cnt[word[right]]) {
cnt.erase(word[right]);
}
}
result += right - left;
}
return result;
}
};
// Time: O(n)
// Space: O(1)
class Solution2 {
public:
int countVowelSubstrings(string word) {
static const int k = 5;
return atMostK(word, k) - atMostK(word, k - 1);
}
private:
int atMostK(const string& word, int k) {
static const unordered_set<int> VOWELS = {'a', 'e', 'i', 'o', 'u'};
unordered_map<int, int> cnt;
int result = 0, left = 0;
for (int right = 0; right < size(word); ++right) {
if (!VOWELS.count(word[right])) {
cnt.clear();
left = right + 1;
continue;
}
++cnt[word[right]];
for (; size(cnt) > k; ++left) {
if (!--cnt[word[left]]) {
cnt.erase(word[left]);
}
}
result += right - left + 1;
}
return result;
}
};