2559. 统计范围内的元音字符串数
2559. 统计范围内的元音字符串数
题目
You are given a 0-indexed array of strings words
and a 2D array of integers queries
.
Each query queries[i] = [li, ri]
asks us to find the number of strings present in the range li
to ri
(both inclusive) of words
that start and end with a vowel.
Return an arrayans
of sizequeries.length
, whereans[i]
is the answer to thei
th query.
Note that the vowel letters are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
Example 1:
Input: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
Output: [2,3,0]
Explanation: The strings starting and ending with a vowel are "aba", "ece", "aa" and "e".
The answer to the query [0,2] is 2 (strings "aba" and "ece").
to query [1,4] is 3 (strings "ece", "aa", "e").
to query [1,1] is 0.
We return [2,3,0].
Example 2:
Input: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]
Output: [3,2,1]
Explanation: Every string satisfies the conditions, so we return [3,2,1].
Constraints:
1 <= words.length <= 10^5
1 <= words[i].length <= 40
words[i]
consists only of lowercase English letters.sum(words[i].length) <= 3 * 10^5
1 <= queries.length <= 10^5
0 <= li <= ri < words.length
题目大意
给你一个下标从 0 开始的字符串数组 words
以及一个二维整数数组 queries
。
每个查询 queries[i] = [li, ri]
会要求我们统计在 words
中下标在 li
到 ri
范围内(包含这两个值)并且以元音开头和结尾的字符串的数目。
返回一个整数数组,其中数组的第 i
个元素对应第 i
个查询的答案。
注意: 元音字母是 'a'
、'e'
、'i'
、'o'
和 'u'
。
示例 1:
输入: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
输出:[2,3,0]
解释: 以元音开头和结尾的字符串是 "aba"、"ece"、"aa" 和 "e" 。
查询 [0,2] 结果为 2(字符串 "aba" 和 "ece")。
查询 [1,4] 结果为 3(字符串 "ece"、"aa"、"e")。
查询 [1,1] 结果为 0 。
返回结果 [2,3,0] 。
示例 2:
输入: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]
输出:[3,2,1]
解释: 每个字符串都满足这一条件,所以返回 [3,2,1] 。
提示:
1 <= words.length <= 10^5
1 <= words[i].length <= 40
words[i]
仅由小写英文字母组成sum(words[i].length) <= 3 * 10^5
1 <= queries.length <= 10^5
0 <= queries[j][0] <= queries[j][1] < words.length
解题思路
为优化查询效率,可以使用前缀和的思想。
前缀和数组:
- 维护一个
prefixCount
数组,其中prefixCount[i]
表示从索引0
到i-1
的符合条件的字符串数量。 - 初始化
prefixCount[0] = 0
,方便计算差值。 - 遍历
words
数组,逐步统计符合条件的字符串数量并更新到prefixCount
中。
- 维护一个
查询计算:
- 对每个查询
(l, r)
,结果等于:result = prefixCount[r + 1] - prefixCount[l]
- 通过前缀和的性质,可以在
O(1)
时间内计算出结果。
- 对每个查询
复杂度分析
- 时间复杂度:
O(n + m)
,- 前缀和计算:
O(n)
,其中n
是words
的长度。 - 查询处理:
O(m)
,其中m
是queries
的长度。
- 前缀和计算:
- 空间复杂度:
O(n + m)
,维护了一个长度为n
的前缀和数组,和一个长度为m
的结果数组。
代码
/**
* @param {string[]} words
* @param {number[][]} queries
* @return {number[]}
*/
var vowelStrings = function (words, queries) {
const vowels = new Set('aeiou');
let prefixCount = [0];
let count = 0;
// 构建前缀和数组
for (let word of words) {
if (vowels.has(word[0]) && vowels.has(word[word.length - 1])) {
count++;
}
prefixCount.push(count);
}
// 处理查询
let res = [];
for (let [l, r] of queries) {
res.push(prefixCount[r + 1] - prefixCount[l]);
}
return res;
};
相关题目
题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
---|---|---|---|---|---|
1871 | 跳跃游戏 VII | 字符串 动态规划 前缀和 1+ | 🟠 | 🀄️ 🔗 |