Reverse Vowels of a String in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase string. Our task is to reverse the vowels present in the string. So if the string is “hello”, then the string after vowel reversal will be “holle”. For string “programming”, it will be “prigrammong”

To solve this, we will follow these steps −

  • Take the string and make a list of vowels, and store their indices as well
  • reverse the vowel list
  • set idx := 0
  • for i := 0 to length of given string – 1
    • if i is in index list −
      • put vowels[i] into final string
      • idx := idx + 1
    • otherwise put string[i] into final string
  • return the list as a string

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def reverseVowels(self, s):
      chars = list(s)
      index = []
      vowels = []
      for i in range(len(chars)):
         if chars[i] in ['a','e','i','o','u']:
         vowels.append(chars[i])
         index.append(i)
      vowels = vowels[::-1]
      final = []
      ind = 0
      for i in range(len(chars)):
      if i in index:
         final.append(vowels[ind])
         ind += 1
      else:
         final.append(chars[i])
   str1 = ""
   return str1.join(final)
ob1 = Solution()
print(ob1.reverseVowels("hello"))
print(ob1.reverseVowels("programming"))

Input

"hello"
"programming"

Output

holle
prigrammong
raja
Published on 16-Jan-2020 15:05:41
Advertisements