2559. Count Vowel Strings in Ranges #1050
-
Topics: You are given a 0-indexed array of strings Each query Return an array Note that the vowel letters are Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can follow these steps:
Let's implement this solution in PHP: 2559. Count Vowel Strings in Ranges <?php
/**
* @param String[] $words
* @param Integer[][] $queries
* @return Integer[]
*/
function vowelStrings($words, $queries) {
// Step 1: Precompute prefix sums
$n = count($words);
$prefixSum = array_fill(0, $n + 1, 0);
for ($i = 0; $i < $n; $i++) {
$prefixSum[$i + 1] = $prefixSum[$i] + ($this->isVowelString($words[$i]) ? 1 : 0);
}
// Step 2: Answer queries using the prefix sum
$result = [];
foreach ($queries as $query) {
list($l, $r) = $query;
$result[] = $prefixSum[$r + 1] - $prefixSum[$l];
}
return $result;
}
/**
* Helper function to check if a string starts and ends with a vowel
*
* @param $word
* @return bool
*/
function isVowelString($word) {
$vowels = ['a', 'e', 'i', 'o', 'u'];
$n = strlen($word);
return in_array($word[0], $vowels) && in_array($word[$n - 1], $vowels);
}
// Example 1
$words1 = ["aba", "bcb", "ece", "aa", "e"];
$queries1 = [[0, 2], [1, 4], [1, 1]];
print_r(countVowelStringsInRanges($words1, $queries1)); // Output: [2, 3, 0]
// Example 2
$words2 = ["a", "e", "i"];
$queries2 = [[0, 2], [0, 1], [2, 2]];
print_r(countVowelStringsInRanges($words2, $queries2)); // Output: [3, 2, 1]
?> Explanation:
Edge Cases:
This approach efficiently handles the constraints of the problem. |
Beta Was this translation helpful? Give feedback.
We can follow these steps:
Let's implement this solution in PHP: 2559. Count Vowel Strings in Ranges