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

Table of Contents

Question

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.

Python Solution

class Solution:
    def reverseVowels(self, s: str) -> str:
        s=list(s)
        vowels = set(list('aeiouAEIOU'))
        l=0
        r=len(s)-1

        while l<r:
            if s[l] in vowels and s[r] in vowels:
                s[l],s[r] = s[r],s[l]
                l+=1
                r-=1
            if s[l] not in vowels:
                l+=1
            if s[r] not in vowels:
                r-=1
        return (''.join(s))

Leave a Reply

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