LeetCode 345. Reverse Vowels of a String

Description

https://leetcode.com/problems/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 cases.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

Explanation

Build a result list. Iterate the string, if the character visiting is vowels, append None to the list and append the vowel to vowels list, otherwise, just append the character. Finally add vowels in reverse order to replace None’s in the results list.

Python Solution

class Solution:
    def reverseVowels(self, s: str) -> str:
        
        vowels = {'a', 'e', 'i', 'o', 'u'}
        
        results = []
        
        vowels_in_s = []
        
        for c in s:
            if c.lower() in vowels:
                vowels_in_s.append(c)
                results.append(None)
            else:
                results.append(c)        
        
        for i, item in enumerate(results):
            if not item:
                results[i] = vowels_in_s.pop()
        
        
        return "".join(results)
                
  • Time Complexity: O(N).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *