[LeetCode] 2559. Count Vowel Strings in Ranges
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 array ans of size queries.length, where ans[i] is the answer to the ith 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 <= 105
1 <= words[i].length <= 40
words[i] consists only of lowercase English letters.
sum(words[i].length) <= 3 * 105
1 <= queries.length <= 105
0 <= li <= ri < words.length
统计范围内的元音字符串数。
给你一个下标从 0 开始的字符串数组 words 以及一个二维整数数组 queries 。每个查询 queries[i] = [li, ri] 会要求我们统计在 words 中下标在 li 到 ri 范围内(包含 这两个值)并且以元音开头和结尾的字符串的数目。
返回一个整数数组,其中数组的第 i 个元素对应第 i 个查询的答案。
注意:元音字母是 'a'、'e'、'i'、'o' 和 'u' 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-vowel-strings-in-ranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
思路是前缀和。这是前缀和的基础应用。如果 input 数组的长度是 n,那么我们需要一个长度为 n + 1 的数组记录前 n 个单词里面有多少个单词是以元音开头和结尾的。然后我们就可以以O(1)
的时间找到下标在 li 到 ri 范围内(包含 这两个值)并且以元音开头和结尾的字符串的数目。
复杂度
时间O(n)
空间O(n)
代码
Java实现
class Solution {
public int[] vowelStrings(String[] words, int[][] queries) {
int n = words.length;
int[] presum = new int[n + 1];
presum[0] = 0;
for (int i = 0; i < n; i++) {
int cur = helper(words[i]) == true ? 1 : 0;
presum[i + 1] = presum[i] + cur;
}
int len = queries.length;
int[] res = new int[len];
for (int i = 0; i < len; i++) {
int left = queries[i][0];
int right = queries[i][1];
res[i] = presum[right + 1] - presum[left];
}
return res;
}
private boolean helper(String str) {
char first = str.charAt(0);
char last = str.charAt(str.length() - 1);
return isVowel(first) && isVowel(last);
}
private boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}