JAVA using two pointers


  • 0
    E
    public class Solution {
        public String reverseVowels(String s) {
            // sanity check
            if (s == null || s.length() == 0) {
                return s;
            }
            char[] s1 = s.toCharArray();
            int i = 0;
            int j = s1.length - 1;
            while (i < j) {
                if (check(s1[i]) && check(s1[j])) {
                    swap(s1, i, j);
                    i++;
                    j--;
                } else if (check(s1[i])) {
                    j--;
                } else if (check(s1[j])) {
                    i++;
                } else {
                    i++;
                    j--;
                }
            }
            return new String(s1);
        }
        
        private void swap(char[] input, int i, int j) {
            char temp = input[i];
            input[i] = input[j];
            input[j] = temp;
        }
        
        private boolean check(char s) {
            char[] ch = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
            for (char c : ch) {
                if (s == c) {
                    return true;
                }
            }
            return false;
        }
    }
    

Log in to reply
 

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