统计范围内的元音字符串数
难度:
标签:
题目描述
You are given a 0-indexed array of string words
and two integers left
and right
.
A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
Return the number of vowel strings words[i]
where i
belongs to the inclusive range [left, right]
.
Example 1:
Input: words = ["are","amy","u"], left = 0, right = 2 Output: 2 Explanation: - "are" is a vowel string because it starts with 'a' and ends with 'e'. - "amy" is not a vowel string because it does not end with a vowel. - "u" is a vowel string because it starts with 'u' and ends with 'u'. The number of vowel strings in the mentioned range is 2.
Example 2:
Input: words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4 Output: 3 Explanation: - "aeo" is a vowel string because it starts with 'a' and ends with 'o'. - "mu" is not a vowel string because it does not start with a vowel. - "ooo" is a vowel string because it starts with 'o' and ends with 'o'. - "artro" is a vowel string because it starts with 'a' and ends with 'o'. The number of vowel strings in the mentioned range is 3.
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 10
words[i]
consists of only lowercase English letters.0 <= left <= right < words.length
代码结果
运行时间: 24 ms, 内存: 16.6 MB
// 思路:
// 1. 使用 Java Stream 处理从 left 到 right 范围内的 words 数组。
// 2. 过滤出以元音字母开头并以元音字母结尾的字符串。
// 3. 统计满足条件的字符串数量并返回。
import java.util.Arrays;
public class VowelStringCounterStream {
public static int countVowelStrings(String[] words, int left, int right) {
String vowels = "aeiou";
return (int) Arrays.stream(words, left, right + 1)
.filter(word -> vowels.indexOf(word.charAt(0)) != -1 && vowels.indexOf(word.charAt(word.length() - 1)) != -1)
.count();
}
public static void main(String[] args) {
String[] words1 = {"are", "amy", "u"};
int left1 = 0, right1 = 2;
System.out.println(countVowelStrings(words1, left1, right1)); // 输出:2
String[] words2 = {"hey", "aeo", "mu", "ooo", "artro"};
int left2 = 1, right2 = 4;
System.out.println(countVowelStrings(words2, left2, right2)); // 输出:3
}
}
解释
方法:
这个题解使用了列表推导和 Python 的内置函数 sum 来统计元音字符串的数量。首先,对于 words 数组中的索引从 left 到 right 的每个元素(即字符串),检查该字符串的第一个字符和最后一个字符是否都是元音字母('a', 'e', 'i', 'o', 'u')。如果两个条件都满足,则该字符串被认为是元音字符串。列表推导会为每个元音字符串生成 True,非元音字符串生成 False。最后,使用 sum 函数计算列表中 True 的总数,即为所求的元音字符串数量。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
题解中提到使用列表推导和 sum 函数来统计元音字符串,这种方法在处理大数据量时的效率如何?
▷🦆
在题解中,如果输入的 'words' 数组为空或者 'left' 和 'right' 指定的范围不包含任何元素,这种情况下的输出是什么?
▷🦆
题解考虑了字符串首尾字符是元音字母的情况,但是如果字符串长度为0,即空字符串,这种情况是否会导致错误?
▷🦆
题解中使用了 's[0] in "aeiou" and s[-1] in "aeiou"' 来判断元音字符串,为什么不直接创建一个元音集合来进行查找是否更高效?
▷