DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 345. Reverse Vowels of a String

Image description

Naive Approach

/**
 * @param {string} s
 * @return {string}
 */
var reverseVowels = function(s) {

    const myStack = [];

    const vowels = ["a","e","i","o","u","A",'E',"I","O","U"];

    const res = []

    for(let i=0;i<s.length;i++){
        if(vowels.includes(s[i])){
            myStack.push(s[i])
            res.push("*")
        }else{
            res.push(s[i])
        }
    }

    for(let i=0;i<s.length;i++){
        if(res[i]=="*"){
            res[i] = myStack.pop()
        }
    }
    return res.join('')
};
Enter fullscreen mode Exit fullscreen mode

Using Regex

const reverseVowels = function(s) {
    // Extract all vowels from the string, ignoring case
    const vowels = s.match(/[aeiou]/gi) || [];

    // Replace each vowel in the string with the reversed order of vowels
    return s.replace(/[aeiou]/ig, () => vowels.pop());
};
Enter fullscreen mode Exit fullscreen mode

g (Global Flag) -> global flag it wont stop after matching one case , it checks in entire string
i (Ignore Case Flag) -> ignores the casing

Two Pointers Approach

const vowels = ['a', 'e', 'i', 'o', 'u'];

var reverseVowels = function(s) {
    let output = s.split('');
    let cursor1 = 0;
    let cursor2 = s.length - 1;

    while (cursor1 < cursor2) {
        if (vowels.includes(s[cursor1].toLowerCase()) && vowels.includes(s[cursor2].toLowerCase())) {
            [output[cursor1], output[cursor2]] = [output[cursor2], output[cursor1]];
            cursor1++;
            cursor2--;
        }
        if (!vowels.includes(s[cursor1].toLowerCase())) {
            cursor1++;
        }
        if (!vowels.includes(s[cursor2].toLowerCase())) {
            cursor2--;
        }
    }

    return output.join('');
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)