codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Leetcode] Reverse vowels #41

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

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

Example 1:

Input: "hello" Output: "holle" Example 2:

Input: "leetcode" Output: "leotcede"

lpatmo commented 5 years ago
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
    "eo" //loop over once, find vowels
    "holle" //loop over a second time, build up the string
    let buildStr = "";
    let vowels = "";

    for (let i=0; i<s.length; i++){
        if ("AEIOUaeiou".includes(s[i])) {
            vowels+=s[i];
        }
    }
    let pointer = vowels.length-1;
    for (let i=0; i<s.length; i++) {
        if ("AEIOUaeiou".includes(s[i])) {
            buildStr+=vowels[pointer]
            pointer--;
        } else {
            buildStr+=s[i];
        }
    }

    return buildStr;
};