To solve this problem, we need to filter words from a given list that consist only of vowels. The solution involves checking each character of a word to ensure it is a vowel, and if any character is not a vowel, we skip that word.
Approach
- Initialize Result List: Create an empty list to store the valid words (those consisting only of vowels).
- Iterate Over Words: For each word in the input list:
- Check Each Character: For each character in the word, verify if it is a vowel (a, e, i, o, u).
- Flag Invalid Words: If any character is not a vowel, mark the word as invalid and stop checking further characters in that word (using
breakto optimize).
- Add Valid Words: If all characters of a word are vowels, add the word to the result list.
Solution Code
class Solution:
def solve(self, words):
res = []
vowels = {'a', 'e', 'i', 'o', 'u'} # Set of vowels
for word in words:
flag = True
for c in word:
if c not in vowels: # Check if character is not a vowel
flag = False
break # Stop checking further characters in this word
if flag:
res.append(word)
return res
Explanation
- Vowel Set: The set
vowelscontains all lowercase vowels. This allows O(1) time complexity for checking if a character is a vowel. - Flag: The
flagvariable tracks whether the current word is valid (all vowels). If any non-vowel character is found,flagis set toFalseand we break out of the inner loop to avoid unnecessary checks. - Result: Valid words (those with all vowels) are added to the result list, which is returned at the end.
This approach efficiently filters the words with a time complexity of O(N * M), where N is the number of words and M is the average length of the words. This is optimal for this problem as each character must be checked at least once.

作者声明:本文包含人工智能生成内容。