You are given a string array words with subscripts starting from 0 and a two-dimensional integer array queries.
Each query queries[i] = [li, ri] would ask us to count the number of strings in words with subscripts in the range li to ri (inclusive) that start and end with a vowel.
Returns an array of integers where the ith element of the array corresponds to the answer to the ith query.
Note: The vowels 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 that start and end with vowels are "aba", "ece", "aa" and "e".
The query [0,2] results in 2 (the strings "aba" and "ece").
The query [1,4] results in 3 (the strings "ece", "aa", "e").
The query [1,1] results in 0.
Returns the result [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 this condition, so [3,2,1] is returned.
Source: LeetCode
Link: https://leetcode.cn/problems/count-vowel-strings-in-ranges
The copyright belongs to LeetCode. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.
Idea: prefix sum. For each query, count the number in the interval.
class Solution {
public:
vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
int n = words.size() ;
vector<int> ans ;
vector<int> w(26,0) ;
string ps = "aeiou" ;
for(char p :ps ){
w[p-'a']++ ;
}
vector<int> a(n) ;;
for(int i = 0 ; i<n ; i++ ){
if(isVowel(words[i] ,w)){
a[i] = 1 ;
}
}
vector<int> sum(n+1) ;
for(int i =1 ; i<=n ; i++ ){
sum[i] = sum[i-1]+a[i-1] ;
}
for(int i = 0 ; i<queries.size() ; i ++ ) {
int l = queries[i][0] ;
int r = queries[i][1] ;
// cout<<l <<" " << r<< endl ;
int rt = sum[r+1] -sum[l] ;
// cout<<<<endl;
ans.push_back(rt) ;
}
return ans ;
}
// 判断是否是字符串是否符合要求
bool isVowel(string s ,vector<int> w ){
if(w[s[0] -'a'] >0 && w[s[s.size()-1] -'a'] >0)return true ;
return false ;
}
};