Leetcode | Reverse Vowels of a String (反转字符串中的元音字符)

本文探讨了一种常见的字符串问题,即反转字符串中的元音。通过对比两种不同的Python实现方式,一种使用列表,另一种利用字典,展示了如何通过字典提高算法效率。作者通过实例分析了字典遍历速度比列表快的优势,并给出了执行时间和内存消耗的数据。文章最后总结了在Python中,字典在查找操作上的高效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:

Write a function that takes a string as input and reverse only the vowels of a string.
Attention:Vowels include captial letters(大写字母)

Example:

Input: “hello”
Output: “holle”

Input: “leetcode”
Output: “leotcede”

Ideas:

This's a typical problem solved with pointers.

My code:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        s_list = list(s)
        i = 0
        j = len(s_list) - 1
        while (i < j):
            x = s_list[i]
            y = s_list[j]
            if (x in vowels) and (y in vowels):
                temp = s_list[i]
                s_list[i] = y
                s_list[j] = temp
                i += 1
                j -= 1
            elif (x not in vowels):
                i += 1
            elif (y not in vowels):
                j -= 1
        return ''.join(s_list)

Execution time:80ms
Memory consumption:15.1MB

Discovery:

Dict traverse much faster then List traverse.

# use dict
def reverseVowels(s):
    """
    :type s: str
    :rtype: str
    """
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    s_list = list(s)
    i = 0
    j = len(s_list) - 1
    while (i < j):
        x = s_list[i]
        y = s_list[j]
        if (x in vowels) and (y in vowels):
            s_list[i], s_list[j] = s_list[j], s_list[i] 
            i += 1
            j -= 1
        elif (x not in vowels):
            i += 1
        elif (y not in vowels):
            j -= 1
    return ''.join(s_list)

Execution time:36ms
Memory consumption:15.2MB

summary

In python, Dict can just have key and use it for searching while value is none.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值