My straight forward solution in Java


  • 0
    public String reverseVowels(String s) {
            if(s == null || s.length() == 0) return s;
            
            Character[] vowel= {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
            List<Character> vowels = new ArrayList(Arrays.asList(vowel));
            
            char[] str = s.toCharArray();
            int left = 0, right = s.length() - 1;
            while(left < right){
                Character c1 = s.charAt(left), c2 = s.charAt(right);
                if(!vowels.contains(c1) && !vowels.contains(c2)){ left ++; right --; continue;}
                if(vowels.contains(c1) && !vowels.contains(c2)){ right --; continue; }
                if(!vowels.contains(c1) && vowels.contains(c2)){ left ++; continue; }
                swap(str, left ++, right --);
            }
            return String.valueOf(str);
        }
        public void swap(char[] str, int i, int j){
            Character c = str[i];
            str[i] = str[j];
            str[j] = c;
        }
    

Log in to reply
 

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