Simple Java solution.


  • 0
    V
    class Solution {
        public String reverseVowels(String s) {
            int i = 0;
            int j = s.length() - 1;
            char[] word = s.toCharArray();
            
            Set<Character> set = new HashSet<Character>();
            set.add('a');
            set.add('e');
            set.add('i');
            set.add('o');
            set.add('u');
            set.add('A');
            set.add('E');
            set.add('I');
            set.add('O');
            set.add('U');
            
            while (i < j) {
                if (set.contains(word[i]) && set.contains(word[j])) {
                    char temp = word[i];
                    word[i] = word[j];
                    word[j] = temp;
                    i++;
                    j--;
                } else if (!set.contains(word[i]) && !set.contains(word[j])) {
                    i++;
                    j--;
                } else if (!set.contains(word[i])) {
                    i++;
                } else if (!set.contains(word[j])) {
                    j--;
                } 
            }
            return new String(word);
        }
    }
    

Log in to reply
 

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