Reverse Vowels of a String

Given a string s, reverse only all the vowels in the string and return it.

Example 1
Input: "hello" → Output: "holle"
Example 2
Input: "leetcode" → Output: "leotcede"

Solution Approach

Two pointers. Move left pointer right until it hits a vowel. Move right pointer left until it hits a vowel. Swap and continue.

  • Set vowels = {a,e,i,o,u,A,E,I,O,U}.
  • lo=0, hi=n-1.
  • While lo
  • Swap chars[lo] and chars[hi], lo++, hi--.
Java
import java.util.*;

class Solution {
    public String reverseVowels(String s) {
        Set<Character> vowels = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
        char[] c = s.toCharArray();
        int lo = 0, hi = c.length - 1;
        while (lo < hi) {
            while (lo < hi && !vowels.contains(c[lo])) lo++;
            while (lo < hi && !vowels.contains(c[hi])) hi--;
            if (lo < hi) { char t = c[lo]; c[lo] = c[hi]; c[hi] = t; lo++; hi--; }
        }
        return new String(c);
    }
}
  • Time Complexity: O(N)
  • Space Complexity: O(1) extra