LeetCode 345

345. Reverse Vowels of a String

Problem

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.

Solution

Approach

First, we want to visualize how we are going to iterate through the string. If we are wanting to swap two vowels we can use a two pointer approach. Since we are using two pointers and only changing those two values we can do all the modifications in place saving space. We want to loop through the string until the right pointer has equal the left pointer. At each iteration if a a character is a vowel we must copy left and right characters and swap.

Helper Function

I created a helper function to check if a character is a vowel or not. In the prompt we can see what letters we must consider as a vowel.

class Solution:
    def reverseVowels(self, s: str) -> str:
        def isVowel(c):
            return c.lower() in ["a", "e", "i", "o", "u"]

        left = 0
        right = len(s) - 1
        s = list(s)

        while left < right:
            if isVowel(s[left]):
                while(isVowel(s[right]) == False):
                    right -= 1
                    
                l = s[left]
                r = s[right]
                s[left] = r
                s[right] = l
                right -= 1

            left += 1

        return "".join(s)