LeetCode 题解工作台
统计范围内的元音字符串数
给你一个下标从 0 开始的字符串数组 words 和两个整数: left 和 right 。 如果字符串以元音字母开头并以元音字母结尾,那么该字符串就是一个 元音字符串 ,其中元音字母是 'a' 、 'e' 、 'i' 、 'o' 、 'u' 。 返回 words[i] 是元音字符串的数目,其中 i…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们只需要遍历区间 $[left,.. right]$ 内的字符串,判断其是否以元音字母开头和结尾即可。若是,则答案加一。 遍历结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个下标从 0 开始的字符串数组 words 和两个整数:left 和 right 。
如果字符串以元音字母开头并以元音字母结尾,那么该字符串就是一个 元音字符串 ,其中元音字母是 'a'、'e'、'i'、'o'、'u' 。
返回 words[i] 是元音字符串的数目,其中 i 在闭区间 [left, right] 内。
示例 1:
输入:words = ["are","amy","u"], left = 0, right = 2 输出:2 解释: - "are" 是一个元音字符串,因为它以 'a' 开头并以 'e' 结尾。 - "amy" 不是元音字符串,因为它没有以元音字母结尾。 - "u" 是一个元音字符串,因为它以 'u' 开头并以 'u' 结尾。 在上述范围中的元音字符串数目为 2 。
示例 2:
输入:words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4 输出:3 解释: - "aeo" 是一个元音字符串,因为它以 'a' 开头并以 'o' 结尾。 - "mu" 不是元音字符串,因为它没有以元音字母开头。 - "ooo" 是一个元音字符串,因为它以 'o' 开头并以 'o' 结尾。 - "artro" 是一个元音字符串,因为它以 'a' 开头并以 'o' 结尾。 在上述范围中的元音字符串数目为 3 。
提示:
1 <= words.length <= 10001 <= words[i].length <= 10words[i]仅由小写英文字母组成0 <= left <= right < words.length
解题思路
方法一:模拟
我们只需要遍历区间 内的字符串,判断其是否以元音字母开头和结尾即可。若是,则答案加一。
遍历结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 。
class Solution:
def vowelStrings(self, words: List[str], left: int, right: int) -> int:
return sum(
w[0] in 'aeiou' and w[-1] in 'aeiou' for w in words[left : right + 1]
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should focus on correct string boundary checks.
- question_mark
Efficiency should be discussed, especially for larger input sizes.
- question_mark
Look for understanding of how the 'left' and 'right' bounds limit the solution scope.
常见陷阱
外企场景- error
Failing to correctly check the first and last characters of the string.
- error
Not handling edge cases like very short strings or strings that do not have vowels at both ends.
- error
Ignoring array boundaries and accidentally accessing indices outside the given range.
进阶变体
外企场景- arrow_right_alt
What if the strings are larger or the input size increases significantly?
- arrow_right_alt
Can this solution be optimized to handle additional constraints?
- arrow_right_alt
How would you handle a situation where the 'left' and 'right' range values are the same?