leetcode之Reverse Vowels of a String(345)

题目:

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:
给定 s = "hello", 返回 "holle".

示例 2:
给定 s = "leetcode", 返回 "leotcede".

注意:
元音字母不包括 "y".

python代码:

class Solution:
    def reverseVowels(self, s):
        res = list(s)
        vowels = []
        for i in range(len(res)):
            if res[i] in ['a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U']:
                vowels.append((i, res[i]))
        for j in range(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)

心得:如果碰到['h', 'e', 'l', 'l', 'o'],想把它变成‘hello’,可以使用''.join(['h', 'e', 'l', 'l', 'o'])。

猜你喜欢

转载自blog.csdn.net/cuicheng01/article/details/81327441