DEV Community

Dwiki
Dwiki

Posted on

Leetcode75 - Reverse vowels in a string #5

This is the 5th problem in Leetcode75 ( Array&Hashing ).

Problem Statement

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 Strategy

  1. we're gonna create a variable that holds an array of strings of vowels
  2. also create a variable that holds a list of given string, since string in python is immutable, we need to do it on a list
  3. create 2 variables for pointer, left and right, left starts at first index of given string, and right starts at the last index of given string
  4. then we will do a while-loop while left < right
  5. we check if the character in left and right index are vowels ( by checking if its in the array that contains vowel that we crated), if yes then swap it , if no then ->
  6. check if the character in left index is vowel then, we decrease the value of right
  7. otherwise we increase the value of left, ( moving the pointer ) until the 5th conditions are met

code:


class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = ['a','i','u','e','o']

        s_list = list(s)

        left = 0
        right = len(s) - 1

        while left < right:
            if s_list[left].lower() in vowels and s_list[right].lower() in vowels:
                temp = s_list[left]
                s_list[left] = s_list[right]
                s_list[right] = temp
                left += 1
                right -= 1

            elif s_list[left].lower() in vowels:
                right -= 1 
            else:
                left += 1 


        return ''.join(s_list)```

Enter fullscreen mode Exit fullscreen mode

Top comments (0)