Leetcode: Reverse Vowels of a String

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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## Blog link: https://code.dennyzhang.com/reverse-vowels-of-a-string
## Basic Ideas: save vowels in an separated array
## Complexity: Time O(n), Space O(n)
class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowel_letters = 'aeiouAEIOU'
        length = len(s)
        vowel_list = []
        for ch in s:
            if ch in vowel_letters:
                vowel_list.append(ch)

        # reverse
        vowel_list = vowel_list[::-1]

        ret = [''] * length

        k = 0
        for i in range(0, len(s)):
            if s[i] in vowel_letters:
                ret.append(vowel_list[k])
                k += 1
            else:
                ret.append(s[i])

        return ''.join(ret)
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.