Reverse Vowels of a String

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"

Solution

public class Solution {
    public string ReverseVowels(string s) {
        string vowel = "aeiouAEIOU";
        int left = 0, right = s.Length-1;
        char[] c = s.ToCharArray();
        while(left < right){
            
            while(left < right && vowel.IndexOf(c[left]) == -1){
                left++;
            }
            
            while(left < right && vowel.IndexOf(c[right]) == -1){
                right--;
            }
            
            char temp = c[left];
            c[left] = c[right];
            c[right] = temp;
            
            left++;
            right--;
        }
        return new string(c);
    }
}

Time Complexity: O(n)

Space Complexity: O(1)

Leave a Comment

Your email address will not be published. Required fields are marked *