DEV Community

codingpineapple
codingpineapple

Posted on

3 1

LeetCode 345. Reverse Vowels of a String (javascript solution)

Description:

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

Solution:

Time Complexity : O(n)
Space Complexity: O(1)

// Two pointers
var reverseVowels = function(s) {
    // Helper function to check if the current letter is a vowel
    function isVowel(letter) {
        const vowels = {
            a: 'a', e:'e', i:'i', o: 'o', u:'u'
        }
        return vowels[letter.toLowerCase()]
    }

    // Left and right pointers
    let left = 0, right = s.length-1
    // Split s into an array so we can swap letters (string are immuatable)
    s = s.split('')
    while(left < right) {
        // Check if pointers are pointing to a vowel
        const l = isVowel(s[left]), r = isVowel(s[right])
        // If both are vowels swap
        if(l && r) {
            const temp = s[left]
            s[left] = s[right]
            s[right] = temp
            left++
            right--
        } else if(!l && !r) { // If both are not vowels move both pointers
            left++
            right--
        } else if(!l) { // Move left pointer
            left++
        } else { // Mover right pointer
            right--
        }
    }
    // Join array to a string
    return s.join('');
};
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay