Java solution two pointers 4ms


  • 0
    W
    public class Solution {
        public String reverseVowels(String s) {
            int left = 0, right = s.length() - 1;
            char[] str = s.toCharArray();
            boolean[] map = new boolean[128];
            map['a'] = true;
            map['e'] = true;
            map['i'] = true;
            map['o'] = true;
            map['u'] = true;
            map['A'] = true;
            map['E'] = true;
            map['I'] = true;
            map['O'] = true;
            map['U'] = true;
            while (true) {
                while (left < s.length() && !map[str[left]]) {left++;}
                while (right >= 0 && !map[str[right]]) {right--;}
                if (left > right) break;
                swap(str, left++, right--);
            }
            return new String(str);
        }
        
        private void swap(char[] str, int i, int j) {
            char temp = str[i];
            str[i] = str[j];
            str[j] = temp;
        }
    }

Log in to reply
 

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