345. Reverse Vowels of a String [easy] (Python)

该博客介绍了如何使用Python解决LeetCode中的345题,即反转字符串中的元音字母。提供了三种解题思路,包括记录元音位置、仅记录元音字母以及使用双指针法。每种方法都附有相应的代码实现。

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

题目链接

https://leetcode.com/problems/reverse-vowels-of-a-string/

题目原文

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.

题目翻译

写一个函数,输入一个字符串,仅将其中的元音字母逆序。
例子1:输入”hello”,输出”holle”;例子2:输入”leetcode”,输出”leotcede”。

思路方法

首先,要知道哪些是元音字母:a, o, e, i, u, A, O, E, I, U.

思路一

一遍扫描所有字符,记录所有元音字母和它们出现的位置到一个数组中;再扫描这个数组,将元音字母逆序填回原来的字符串相应位置。

代码

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = list(s)
        vowels = []
        for i in xrange(len(res)):
            if res[i] in ['a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U']:
                vowels.append((i, res[i]))
        for j in xrange(len(vowels)/2):
            res[vowels[j][0]] = vowels[len(vowels)-j-1][1]
            res[vowels[len(vowels)-j-1][0]] = vowels[j][1]
        return ''.join(res)

思路二

思路一里面要顺序记录出现的元音字母和位置,但是在第二遍循环时只用考虑记录这些位置上的字母的变化。其实也可以只顺序记录所有的元音字母,第二遍循环重新遍历原始字符串,将遇到的元音字母替换成刚才记录的逆序排列。
如果写的很精简的话,就是下面这样的:

代码

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = re.findall('(?i)[aeiou]', s)
        return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)

思路三

维护两个指针分别从字符串头和尾扫描,每次交换两个指针扫到的元音字母,于是只需遍历一遍字符串就可以完成元音字母逆序。

代码

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = {'a': True, 'o': True, 'e': True, 'i': True, 'u': True, 'A': True, 'O': True, 'E': True, 'I': True, 'U': True}
        res = list(s)
        pos = []
        for i in xrange(len(res)):
            if res[i] in vowels:
                pos.append((i, res[i]))
        for j in xrange(len(pos)/2):
            res[pos[j][0]] = pos[len(pos)-j-1][1]
            res[pos[len(pos)-j-1][0]] = pos[j][1]
        return ''.join(res)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51555552

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值