Leetcode 345. 反转字符串中的元音字母 By Python

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

示例 1:

输入: "hello"
输出: "holle"

示例 2:

输入: "leetcode"
输出: "leotcede"

说明:
元音字母不包含字母"y"。


思路

设立2个指针,一个从索引0开始向右,一个从末尾向前,根据条件进行处理即可

代码

class Solution:
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        yuan = ['a','e','i','o','u','A','E','I','O','U']
        s = list(s)
        
        l = 0
        r = len(s)-1
        while l < r:
            if s[l] in yuan and s[r] in yuan:
                s[l], s[r] = s[r], s[l]
                l += 1
                r -= 1
            elif s[l] in yuan and s[r] not in yuan:
                r -= 1
            elif s[l] not in yuan and s[r] in yuan:
                l += 1
            else:
                l += 1
                r -= 1
        return ''.join(s)
原文地址:https://www.cnblogs.com/MartinLwx/p/9806368.html