Skip to content

345 Reverse Vowels of a String

345. Reverse Vowels of a String

题目: https://leetcode.com/problems/Reverse-Vowels-of-a-String/

难度:

Easy

思路

字符串不可变,所以用list代替,最后join

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = 'aeiou'
        string = list(s)
        i, j = 0, len(s) -1
        while i <= j:
            if string[i].lower() not in vowels:
                i += 1
            elif string[j].lower() not in vowels:
                j -= 1
            else:
                string[i], string[j] = string[j], string[i]
                i += 1
                j -= 1
        return ''.join(string)

正则版本

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)


回到顶部