LeetCode 题解工作台
统计范围内的元音字符串数
给你一个下标从 0 开始的字符串数组 words 以及一个二维整数数组 queries 。 每个查询 queries[i] = [l i , r i ] 会要求我们统计在 words 中下标在 l i 到 r i 范围内( 包含 这两个值)并且以元音开头和结尾的字符串的数目。 返回一个整数数组,其中…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·string
答案摘要
我们可以预处理出所有以元音开头和结尾的字符串的下标,按顺序记录在数组 中。 接下来,我们遍历每个查询 $(l, r)$,通过二分查找在 中找到第一个大于等于 的下标 ,以及第一个大于 的下标 ,那么当前查询的答案就是 $j - i$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个下标从 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 <= 1051 <= words[i].length <= 40words[i]仅由小写英文字母组成sum(words[i].length) <= 3 * 1051 <= queries.length <= 1050 <= queries[j][0] <= queries[j][1] < words.length
解题思路
方法一:预处理 + 二分查找
我们可以预处理出所有以元音开头和结尾的字符串的下标,按顺序记录在数组 中。
接下来,我们遍历每个查询 ,通过二分查找在 中找到第一个大于等于 的下标 ,以及第一个大于 的下标 ,那么当前查询的答案就是 。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 和 的长度。
class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
vowels = set("aeiou")
nums = [i for i, w in enumerate(words) if w[0] in vowels and w[-1] in vowels]
return [bisect_right(nums, r) - bisect_left(nums, l) for l, r in queries]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(M + N) |
| 空间 | O(M) |
面试官常问的追问
外企场景- question_mark
Candidate is able to implement the prefix sum approach to optimize range queries.
- question_mark
Candidate correctly handles the constraints and performs preprocessing efficiently.
- question_mark
Candidate understands the concept of vowel-checking and its application in this problem.
常见陷阱
外企场景- error
Failing to initialize the prefix sum array correctly, especially with respect to boundary conditions.
- error
Not efficiently checking whether a word starts and ends with a vowel, resulting in unnecessary time complexity.
- error
Misunderstanding the problem constraints and attempting to solve it with a brute-force approach, leading to time limit exceeded errors.
进阶变体
外企场景- arrow_right_alt
Instead of counting words starting and ending with vowels, count words starting with a vowel but ending with a consonant.
- arrow_right_alt
Given a range, find the longest valid word within it that starts and ends with a vowel.
- arrow_right_alt
Modify the problem to count strings containing vowels at any positions within the given ranges.