问题 8:统计元音

发布: (2026年1月6日 GMT+8 14:05)
2 min read
原文: Dev.to

Source: Dev.to

示例

count_vowels("hello world")  # → 3
count_vowels("AEIOU")        # → 5

解决方案

def count_vowels(s):
    """
    Counts the number of vowels in a string.
    """
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    count = 0
    for char in s:
        if char in vowels:
            count += 1
    return count

# Test case
print(count_vowels("pooopcycle"))  # Output: 4

逐步讲解

  • 函数定义def count_vowels(s): 创建一个接受字符串 s 的函数。

  • 元音集合vowels = {...} 将所有小写和大写元音存入集合,以实现 O(1) 查找。

  • 计数器初始化count = 0 开始计数。

  • 遍历for char in s: 循环遍历输入字符串的每个字符。

  • 检查并递增

    if char in vowels:
        count += 1

    当当前字符是元音时,count 加一。

  • 返回return count 返回找到的元音总数。

示例追踪 "pooopcycle"

字符是否元音计数
p0
o1
o2
o3
p3
c3
y3
c3
l3
e4

该函数对该输入正确返回 4

祝编码愉快! 💻

Back to Blog

相关文章

阅读更多 »

第85天:100天DSA编码挑战

挑战概述:接受新挑战——每日解答 GeeksforGeeks POTD 并分享我的解法!💻🔥 问题:最小时间满足所有订单 GeeksforGeeks…

100 天 DSA 编码挑战的第 82 天

问题 在二维矩阵中寻找峰值元素 GeeksforGeeks 题目链接 https://www.geeksforgeeks.org/problems/find-the-peak-element-in-a-2d-matrix/1 难度...