Write a function that takes a string as input and returns the string with only the vowels reversed.
Note: The letters “a”, “e”, “i”, “o”, and “u” are vowels. The letter “y” is not a vowel.
s = "hello, world", the output should be
reverseVowelsOfString(s) = "hollo, werld";
s = "codefights", the output should be
reverseVowelsOfString(s) = "cidefoghts";
s = "eIaOyU", the output should be
reverseVowelsOfString(s) = "UOaIye".
- [time limit] 4000ms (py)
- [input] string s
0 ≤ s.length ≤ 50.
- [output] string
We need to find out if a character is a vowel. An easy way to do it in python is to define a string and use
if … in …:
block. We add all the vowels in an array (stack logic). Then, reiterate over the input string and start creating an output string. Everytime we come across a vowel we use the one at the end of the array. If it is a consonant, we just copy that character to the output array.
This is obviously not the most efficient, or even a moderately efficient algorithm.
What we could do aside from this method is, instead of storing the letters, we could have stored the indices of the letters and everytime we came across a vowel, we could swap them with the one that it matches from the end. Let’s say we have 5 (or 6) vowels, we would swap first with last, second with last-1 and third with last-2). After swapping third one, we don’t swap anymore and just return the string. (Because we already swapped everything that has to be swapped)