卖萌的弱渣

I am stupid, I am hungry.

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”.

Note:

The vowels does not include the letter “y”.

Solution

  • Vowels include “AEIOUaeiou”
(Reverse-Vowels-of-a-String.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s:
            return s

        l = 0
        r = len(s)-1
        ret = [i for i in s]
        vowel = "aeiouAEIOU"
        while l < r:
            # find the vowel from left
            while l < r and ret[l] not in vowel:
                l += 1

            # find the vowel from right
            while l < r and ret[r] not in vowel:
                r -= 1

            if l<r:
                ret[l],ret[r] = ret[r],ret[l]
            l += 1
            r -= 1
        return "".join(ret)