[leetcode] 345. Reverse Vowels of a String _ Algorithm Problem Solve for python

1. Problem

345. Reverse Vowels of a String

Given a string s, reverse only all the vowels in the string and return it.

The vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and they can appear in both lower and upper cases, more than once.

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"


  • 1 <= s.length <= 3 * 10^5
  • s consist of printable ASCII characters.

2. Solution

I solved this problem like this.

  • Complexity
    • Time complexity : O(N)
    • Space complexity : O(N)
  • Step
    • Check word is vowels. If word is vowel, push s_vowels list.
    • Change again vowel and change order.
class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = ['a', 'e', 'i', 'o','u', 'A', 'E', 'I', 'O', 'U']
        s_vowels = []
        answer = ''
        for _s in s:
            if _s in vowels:
        idx = 0
        for _s in s:
            if _s in vowels:
                answer += s_vowels[-(idx+1)]
                idx += 1
                answer += _s

        return answer