Leetcode Problem:
Summary
- Count the number of substrings in a given word that contain every vowel at least once and exactly k consonants.
Approach
- Sliding Window Technique with Hash Map, using two helper functions to track vowel and consonant counts.
Complexity
- O(n^2), where n is the length of the word, due to nested loops in the sliding window approach.
Solution Code:
class Solution {
public:
long countOfSubstrings(string word, int k) {
return atLeastK(word, k) - atLeastK(word, k + 1);
}
private:
long atLeastK(string word, int k) {
long numValidSubstrings = 0;
int start = 0;
int end = 0;
// Keep track of counts of vowels and consonants.
unordered_map vowelCount;
int consonantCount = 0;
// Start sliding window.
while (end < word.length()) {
// Insert new letter.
char newLetter = word[end];
// Update counts.
if (isVowel(newLetter)) {
vowelCount[newLetter]++;
} else {
consonantCount++;
}
// Shrink window while we have a valid substring.
while (vowelCount.size() == 5 and consonantCount >= k) {
numValidSubstrings += word.length() - end;
char startLetter = word[start];
if (isVowel(startLetter)) {
if (--vowelCount[startLetter] == 0) {
vowelCount.erase(startLetter);
}
} else {
consonantCount--;
}
start++;
}
end++;
}
return numValidSubstrings;
}
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
};
class Solution {
public:
long countOfSubstrings(string word, int k) {
return atLeastK(word, k) - atLeastK(word, k + 1);
}
private:
long atLeastK(string word, int k) {
long numValidSubstrings = 0;
int start = 0;
int end = 0;
// Keep track of counts of vowels and consonants.
unordered_map vowelCount;
int consonantCount = 0;
// Start sliding window.
while (end < word.length()) {
// Insert new letter.
char newLetter = word[end];
// Update counts.
if (isVowel(newLetter)) {
vowelCount[newLetter]++;
} else {
consonantCount++;
}
// Shrink window while we have a valid substring.
while (vowelCount.size() == 5 and consonantCount >= k) {
numValidSubstrings += word.length() - end;
char startLetter = word[start];
if (isVowel(startLetter)) {
if (--vowelCount[startLetter] == 0) {
vowelCount.erase(startLetter);
}
} else {
consonantCount--;
}
start++;
}
end++;
}
return numValidSubstrings;
}
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
};
'알고리즘' 카테고리의 다른 글
Maximum Count of Positive Integer and Negative Integer (0) | 2025.03.13 |
---|---|
Number of Substrings Containing All Three Characters (0) | 2025.03.11 |
Alternating Groups II (0) | 2025.03.10 |
Minimum Recolors to Get K Consecutive Black Blocks (0) | 2025.03.09 |
Closest Prime Numbers in Range (0) | 2025.03.08 |