内容中心

2026年知名的室内打磨专业公司推荐-泰安振明建筑工程有限公司

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

  1. Initialize Result List: Create an empty list to store the valid words (those consisting only of vowels).
  2. 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 break to optimize).
  3. 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 vowels contains all lowercase vowels. This allows O(1) time complexity for checking if a character is a vowel.
  • Flag: The flag variable tracks whether the current word is valid (all vowels). If any non-vowel character is found, flag is set to False and 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.

泰安振明建筑工程有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?