3306. Count of Substrings Containing Every Vowel and K Consonants II #1414
-
Topics: You are given a string word and a non-negative integer k. Return the total number of Substring1 of Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem requires us to count the number of substrings within a given string Key Points
ApproachWe use the idea of: Substrings with exactly k consonants = Substrings with at most k - Substrings with at most (k-1) Plan
Let's implement this solution in PHP: 3306. Count of Substrings Containing Every Vowel and K Consonants II <?php
/**
* @param String $word
* @param Integer $k
* @return Integer
*/
function countOfSubstrings($word, $k) {
return substringsWithAtMost($word, $k) - substringsWithAtMost($word, $k - 1);
}
/**
* @param $word
* @param $k
* @return int|mixed
*/
function substringsWithAtMost($word, $k) {
if ($k == -1) return 0;
$n = strlen($word);
$res = 0;
$vowels = 0;
$uniqueVowels = 0;
$vowelLastSeen = [];
$vowelList = ['a', 'e', 'i', 'o', 'u'];
foreach ($vowelList as $v) {
$vowelLastSeen[$v] = -1; // Initialize last seen positions
}
$left = 0;
for ($right = 0; $right < $n; ++$right) {
$char = $word[$right];
if (isVowel($char)) {
$vowels++;
if ($vowelLastSeen[$char] < $left) {
$uniqueVowels++;
}
$vowelLastSeen[$char] = $right;
}
// Adjust the left boundary if consonants exceed k
while (($right - $left + 1 - $vowels) > $k) {
$leftChar = $word[$left];
if (isVowel($leftChar)) {
$vowels--;
if ($vowelLastSeen[$leftChar] == $left) {
$uniqueVowels--;
}
}
$left++;
}
// Count substrings if all vowels are present
if ($uniqueVowels == 5) {
$minVowelIndex = min(array_values($vowelLastSeen));
$res += ($minVowelIndex - $left + 1);
}
}
return $res;
}
/**
* @param $char
* @return bool
*/
function isVowel($char) {
return strpos("aeiou", $char) !== false;
}
// Test Cases
echo countOfSubstrings("aeioqq", 1) . "\n"; // Output: 0
echo countOfSubstrings("aeiou", 0) . "\n"; // Output: 1
echo countOfSubstrings("ieaouqqieaouqq", 1) . "\n"; // Output: 3
echo countOfSubstrings("iqeaouqi", 2) . "\n"; // Output: 3
?> Explanation:Function:
|
Beta Was this translation helpful? Give feedback.
The problem requires us to count the number of substrings within a given string
word
that contain all vowels (a, e, i, o, u
) at least once and exactlyk
consonants. We use a sliding window approach to efficiently solve this problem within the given constraints.Key Points
a, e, i, o, u
) at least once.k
consonants.word
is large (up to200,000
characters), so an efficient solution is necessary.Approach
We use the idea of: Substrings with exactly k consonants = Substrings with at most k - Substrings with at most (k-1)
…