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 i
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 <= 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
Solution: Prefix Sum
Let sum[i] := number of valid strings in words[0:i]
For each query [l, r], answer will be sum[r + 1] – sum[l]
Time complexity: O(n + q)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua class Solution { public: vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) { const size_t n = words.size(); vector<int> sum(n + 1); auto check = [](char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; }; for (size_t i = 0; i < n; ++i) sum[i + 1] = sum[i] + (check(words[i][0]) && check(words[i][words[i].size() - 1])); vector<int> ans; for (const auto& q : queries) ans.push_back(sum[q[1] + 1] - sum[q[0]]); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment