给你一个下标从 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 <= 105
1 <= words[i].length <= 40
words[i]
仅由小写英文字母组成sum(words[i].length) <= 3 * 105
1 <= queries.length <= 105
0 <= queries[j][0] <= queries[j][1] < words.length
解法:新建个临时数组(前缀和),存入从(0,index)的数目,然后 最终(a,b)的数目=(0,b)-(0,a-1)
class Solution {
public int[] vowelStrings(String[] words, int[][] queries) {
Set<Character> set = new HashSet<>();
set.add('a');
set.add('e');
set.add('i');
set.add('o');
set.add('u');
int lenWords = words.length;
int lenQue= queries.length;
boolean[] isOK = new boolean[lenWords];
for (int i = 0; i < lenWords; i++) {
String word = words[i];
if (set.contains(word.charAt(0)) &&
set.contains(word.charAt(word.length() - 1))) {
isOK[i] = true;
}
}
int[] temp=new int[lenWords+1];
for (int i = 1; i <= lenWords; i++) {
temp[i]=temp[i-1]+(isOK[i-1]?1:0);
}
int[] res = new int[lenQue];
for (int i = 0; i < lenQue; i++) {
res[i]=temp[queries[i][1]+1]-temp[queries[i][0]];
}
return res;
}
}