LeetCode 题解工作台

统计范围内的元音字符串数

给你一个下标从 0 开始的字符串数组 words 和两个整数: left 和 right 。 如果字符串以元音字母开头并以元音字母结尾,那么该字符串就是一个 元音字符串 ,其中元音字母是 'a' 、 'e' 、 'i' 、 'o' 、 'u' 。 返回 words[i] 是元音字符串的数目,其中 i…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们只需要遍历区间 $[left,.. right]$ 内的字符串,判断其是否以元音字母开头和结尾即可。若是,则答案加一。 遍历结束后,返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串数组 words 和两个整数:leftright

如果字符串以元音字母开头并以元音字母结尾,那么该字符串就是一个 元音字符串 ,其中元音字母是 '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 <= 1000
  • 1 <= words[i].length <= 10
  • words[i] 仅由小写英文字母组成
  • 0 <= left <= right < words.length
lightbulb

解题思路

方法一:模拟

我们只需要遍历区间 [left,..right][left,.. right] 内的字符串,判断其是否以元音字母开头和结尾即可。若是,则答案加一。

遍历结束后,返回答案即可。

时间复杂度 O(m)O(m),空间复杂度 O(1)O(1)。其中 m=rightleft+1m = right - left + 1

1
2
3
4
5
6
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]
        )
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

统计范围内的元音字符串数题解:数组·string | LeetCode #2586 简单