Java - 2 pointers clean and easy to understand solution


  • 0
    T
    public class Solution {
        public String reverseVowels(String s) {
            char[] temp = s.toCharArray();
            int n = temp.length;
            
            int i = 0;
            int j = n-1;
            
            while(i<j){
                //Find the next vowel from the beginning
                while(i<j && !isVowel(temp[i])){
                    i++;
                }
                //Find the next vowel from the end
                while(i<j && !isVowel(temp[j]) ){
                    j--;
                }
                // if both are found and ensure they are not the same, swap them and increase start(i) and decrease end(j) pointer.
                if(i<j){
                    swap(temp,i,j);
                    i++;
                    j--;
                }
            }
            return new String(temp);
        }
        
        private boolean isVowel(char c){
            char t = Character.toLowerCase(c);
            return ( t == 'a' || t == 'e' || t == 'i' || t == 'o' || t == 'u' ) ;
        }
        
        private void swap(char[] c, int i, int j){
            if(i!=j){
                char t = c[i];
                c[i] = c[j];
                c[j] = t;
            }
        }
    }
    

Log in to reply
 

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