345. Reverse Vowels of a String

Description

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".

Solution

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {
    "use strict";
    s = s.split("");
    let ptr1 = 0, ptr2 = s.length-1;
    while (ptr1 < ptr2) {
        if (!/[aeiouAEIOU]/.test(s[ptr1])) {
            ptr1++;
        } else if (!/[aeiouAEIOU]/.test(s[ptr2])) {
            ptr2--;
        } else {
            let tmp = s[ptr1];
            s[ptr1] = s[ptr2];
            s[ptr2] = tmp;
            ptr1++;
            ptr2--;
        }
    }
    return s.join("");
};

results matching ""

    No results matching ""