알고리즘
Count of Substrings Containing Every Vowel and K Consonants II
짬뽕얼큰하게
2025. 3. 10. 23:50
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';
}
};