REVERSE VOWELS OF A STRING | STRING | CODE | CLEAN CODE | INTERVIEW | PROGRAMMING | PRACTICE

By: Saurav

2018-04-01 03:42:00 UTC

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".

Leetcode

If you have solved the string reversal problems without using shortcuts, this problem is simple (not easy)
We need on the hash to identify the indexes of vowels and then run reverse string only for those indexes.

let's see the code:

def reverse_vowels(s)
    
    return s if s.length < 2
    
    vowels = {"a" => 1, "e" => 1, "i" => 1, "o" => 1, "u" => 1, "A" => 1, "E" => 1, "I" => 1, "O" => 1, "U" => 1}
    
    vowel_index = []
    
    (0..s.length-1).each do |i|
      if vowels.key?(s[i])
        vowel_index << i
      end 
    end 
    
   # p vowel_index
    
    
    vowel_index_length = vowel_index.length 
    
    (0..vowel_index_length/2-1).each do |i|
      temp = s[vowel_index[i]]
      s[vowel_index[i]] = s[vowel_index[vowel_index_length - 1 - i]]
      s[vowel_index[vowel_index_length - 1 - i]] = temp
      
      #p s
    end 
    
    return s
end


Let me know what you think!
twitter: sprakash24oct
linkedin

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)