leetcode - 2559. Count Vowel Strings in Ranges

Description

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 <= 10^5
1 <= words[i].length <= 40
words[i] consists only of lowercase English letters.
sum(words[i].length) <= 3 * 10^5
1 <= queries.length <= 10^5
0 <= li <= ri < words.length

Solution

Typical prefix sum. Use a prefix sum hashmap to store the count of all the vowels before current position, then for the query, we just need to prefix[query_end] - prefix[query_start]. Note because the query is inclusive at both sides, we need to twist a little bit.

Time complexity: o ( q u e r y . l e n + w o r d s . l e n ) o(query.len + words.len) o(query.len+words.len)
Space complexity: o ( w o r d s . l e n ) o(words.len) o(words.len)

Code

class Solution:
    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
        prefix_sum = {-1: 0}
        for i in range(len(words)):
            if words[i][0] in ('a', 'e', 'i', 'o', 'u') and words[i][-1] in ('a', 'e', 'i', 'o', 'u'):
                prefix_sum[i] = prefix_sum[i - 1] + 1
            else:
                prefix_sum[i] = prefix_sum[i - 1]
        res = []
        for q_start, q_end in queries:
            q_start -= 1
            res.append(prefix_sum[q_end] - prefix_sum[q_start])
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值