← All problems

2559. Count Vowel Strings in Ranges

MediumOpen on LeetCodeProblem statement

Problem Statement

2559. Count Vowel Strings in Ranges

Medium


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:

C++

Source file
class Solution {
public:
    vector<char> vowels = { 'a', 'e', 'i', 'o', 'u'};
    bool isVowelString(string s){
        int c=0;
        for(auto v:vowels){
            if(v==s.front()) c++;
            if(v==s.back()) c++;
        }
        return c==2;
    }
    
    vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
        vector<int> v = {0};
        for(auto w:words)
            v.push_back(isVowelString(w)?1:0);
        for(int i=1; i<v.size(); i++)
            v[i] += v[i-1];
        v.push_back(v.back());
        vector<int> ans;
        for(auto q: queries)
            ans.push_back(v[q[1]+1]-v[q[0]]);
        return ans;
    }
};