c# solution, O(1) space, O(n) time


  • 0
    M
    public string ReverseVowels(string s)
           {
               if (string.IsNullOrWhiteSpace(s) || s.Length <= 1) return s;            
    
               HashSet<char> vowels = new HashSet<char>() { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
               char[] chars = s.ToCharArray();
               int low = 0;
               int high = s.Length - 1;
               char ch;
    
               while (low < high)
               {
                   while (!vowels.Contains(chars[low]))
                   {
                       low++;
                       if (low == high) return new string(chars);
                   }
                   while (!vowels.Contains(chars[high])) high--;
                   ch = chars[low];
                   chars[low] = chars[high];
                   chars[high] = ch;
                   low++;
                   high--;
               }
               return new string(chars);
           }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.