Javascript Solution


  • 0
    I

    /* alternatively, you can have vowels = 'aeiouAEIOU'
    and use vowels.indexOf(char) > -1
    but accessing a property of an object is faster than using .indexOf */

    var reverseVowels = function(s) {
        var vIndex = {};
        var vowels = {"a":true,"e":true,"i":true,"o":true,"u":true,"A":true,"E":true,"I":true,"O":true,"U":true};
        var reverseV = s.split('');
        reverseV.forEach(function (char, i) {
            if(vowels[char]) {
                vIndex[i] = char;
            }
        });
        if (vIndex.length < 2) return s;
        var keys = Object.keys(vIndex);
        var len = Math.floor(keys.length);
        for(var i = 0; i < len; i++) {
            reverseV[keys[i]] = vIndex[keys[len - 1 - i]];
            reverseV[keys[len - 1 - i]] = vIndex[keys[i]];
        }
        return reverseV.join('');
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.