Reverse Vowels of a String

Reverse Vowels of a String

LeetCode Solution for reversed vowels of a string

ยท

2 min read

Hey there! Welcome back again. In this subsequent article, we'll go through the process of solving the reverse vowels leetcode challenge. Here is the task we're given:
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 lower and upper cases, more than once.

We are tasked with reversing the vowels in a given string, denoted as 's'. We need to check whether the string contains any vowels and then return the string with its vowels reversed. For example, if the string has the value 'hello', it should be transformed to 'holle'. Similarly, if the string has the value 'leetcode', it should be changed to 'leotcede'.

Here's the starter code:

function reverseVowels(s: string): string {

};

To address this challenge, we'll create two arrays: vowels and reversedVowelString. The vowels array will store any existing vowels of the string s while reversedVowelString array will store the string itself. we'll then loop over the string and check if any vowel exists in string s, if it does, we store the vowels in the vowels array. The string s will then be stored in reversedVowelString. We'll run another loop that will iterate over reversedVowelString and replace its vowels with the vowels in vowels array in reverse order. Eventually the array reversedVowelString will be returned as a string.

function reverseVowels(s: string): string {
    let condition = 'AEIOUaeiou';
    let vowel: string[] = []
    let finalWord: string[] = []

    for(let i = 0; i < s.length; i ++) {
        if(condition.includes(s[i])) {
            vowel.push(s[i])
        }
        finalWord.push(s[i])
    }

    for(let i = 0; i < finalWord.length; i ++) {
        if(condition.includes(finalWord[i])) {
            finalWord[i] = vowel.pop() !;
        }
    }
    return finalWord.join('')
};

In conclusion, tackling the reverse vowels LeetCode challenge involves carefully reversing the vowels while keeping the non-vowel characters intact. By creating arrays to store both the vowels and the original string characters, we can effectively manipulate the string to meet the challenge requirements.
Happy coding!!

LinkedIn
Twitter
GitHub

ย