Reverse Vowels Of A String

Solution For Reverse Vowels Of A String

Problem Statement:

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”

Note:

  • The vowels does not include the letter “y”.

Solution:

The problem can be solved by keeping two pointers, one at the start of the string and one at the end. We’ll then swap the vowels at the two positions and move the pointers towards the middle until they meet.

We’ll have to check if a character is a vowel or not. We can do this by creating a set of all the vowels and then checking if a character is in the set or not.

Once we swap the vowels at the two positions, we’ll continue the process until the two pointers meet at the middle.

Code:

“`
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set([‘a’, ‘e’, ‘i’, ‘o’, ‘u’, ‘A’, ‘E’, ‘I’, ‘O’, ‘U’])
s = list(s)
l, r = 0, len(s) – 1

    while l < r:
        if s[l] in vowels and s[r] in vowels:         # Check whether the element is vowel or not
            s[l], s[r] = s[r], s[l]                  # Swap the vowels
            l += 1
            r -= 1
        elif s[l] not in vowels:
            l += 1                                   # Move the left pointer if the character in s[l] is not a vowel
        elif s[r] not in vowels:
            r -= 1                                   # Move the right pointer if the character in s[r] is not a vowel

    return ''.join(s)                                # Return the updated string

“`

Testing:

We’ll test our function with some inputs:

s = Solution()
assert s.reverseVowels("hello") == "holle"
assert s.reverseVowels("leetcode") == "leotcede"
assert s.reverseVowels("aeiou") == "uoiea"
assert s.reverseVowels("bcdfg") == "bcdfg"
assert s.reverseVowels("AaEeIiOoUu") == "UuOoIiEeAa"
print("All test cases passed")

Output:

All test cases passed

Step by Step Implementation For Reverse Vowels Of A String

public class Solution {
    public String reverseVowels(String s) {
        if(s == null || s.length()==0) return s;
        String vowels = "aeiouAEIOU";
        char[] chars = s.toCharArray();
        int start = 0;
        int end = s.length()-1;
        while(start
def reverseVowels(self, s: str) -> str:
        # set pointer variables i and j to the beginning 
        # and end of the input string s, respectively
        i, j = 0, len(s) - 1
        
        # create a list to store the reversed string
        reversed_string = list(s)
        
        # while the pointers have not met in the middle of the string
        while i < j:
            # if the character at index i is not a vowel, 
            # increment i by 1
            if s[i] not in 'aeiouAEIOU':
                i += 1
            # if the character at index j is not a vowel, 
            # decrement j by 1    
            elif s[j] not in 'aeiouAEIOU':
                j -= 1
            # if both characters at indices i and j are vowels,
            # swap them and increment i and decrement j
            else:
                reversed_string[i], reversed_string[j] = reversed_string[j], reversed_string[i]
                i += 1
                j -= 1
                
        # return the reversed string as a string        
        return ''.join(reversed_string)
var reverseVowels = function(s) {
    let i = 0,
        j = s.length - 1,
        res = s.split('');
    while (i < j) {
        while (i < j && !isVowel(res[i])) i++; // find the 1st vowel from left
        while (i < j && !isVowel(res[j])) j--; // find the 1st vowel from right
        [res[i], res[j]] = [res[j], res[i]]; // swap
        i++;
        j--;
    }
    return res.join('');
};

// check if a char is vowel
function isVowel(c) {
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
        c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
class Solution {
public:
    string reverseVowels(string s) {
        int i = 0, j = s.size() - 1;
        while (i < j) {
            i = s.find_first_of("aeiouAEIOU", i);
            j = s.find_last_of("aeiouAEIOU", j);
            if (i < j) {
                std::swap(s[i++], s[j--]);
            }
        }
        return s;
    }
};
public class Solution {
    public string ReverseVowels(string s) {
        int left = 0;
        int right = s.Length - 1;
        StringBuilder sb = new StringBuilder(s);
        while(left < right)
        {
            //if the character at the left index is not a vowel, we increment the left index
            if(!"aeiouAEIOU".Contains(sb[left]))
            {
                left++;
                continue;
            }
            //if the character at the right index is not a vowel, we decrement the right index
            if(!"aeiouAEIOU".Contains(sb[right]))
            {
                right--;
                continue;
            }
            //if the character at the left index is a vowel and the character at the right index is a vowel, we swap them
            char temp = sb[left];
            sb[left] = sb[right];
            sb[right] = temp;
            //increment the left index and decrement the right index
            left++;
            right--;
        }
        return sb.ToString();
    }
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]