➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Reverse Vowels of a String

image

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.

My approach:

We know that we’ll be given a string s and our goal is to reverse only all the vowels in the string and return it

If you look at the example it’s more of they swap the vowels where it’s occurring in the left and right side of the string:

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

So I wrote a script to do the same thing and here’s what it does:

Here’s my solve script: link image

Leetcode Submission Script

class Solution:
    def reverseVowels(self, s: str) -> str:
        s = list(s)
        vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}

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

        while left < right:

            while left < right and s[left] not in vowels:
                left += 1

            while left < right and s[right] not in vowels:
                right -= 1
            
            if s[left] in vowels and s[right] in vowels:
                s[left], s[right] = s[right], s[left]


            left += 1
            right -= 1


        r = "".join(s)
        
        return r