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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s