Java - Simple: Forward and Backwards Pointers


  • 0
    M

    Left counter to move through all letters.

    Right counter coming to the left to find the vowels.

    Uses StringBuilder for efficiency w/appends.

    If not vowel, append. If vowel, then find the next vowel. No need to impose any constraints on right as it inherently must match up with the number of vowels found in left.

    class Solution {
        
        public String reverseVowels(String s) {
        
            StringBuilder tr = new StringBuilder();
            
            int right = s.length()-1;
            
            int left = 0;
            
            while(left < s.length()){
                
                if(isVowel(s.charAt(left))){
                    
                    while(!isVowel(s.charAt(right))){
                        
                        right--;
                        
                    }
                    
                    tr.append(s.charAt(right));
                    
                    right--;
                    
                }else{
                    
                    tr.append(s.charAt(left));
                    
                }
                
                left++;
                
            }
            
            return tr.toString();
            
        }
    
        Boolean isVowel(char c){
            
            if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return true;
            
            if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') return true;
            
            return false;
                    
        }
        
    }

Log in to reply
 

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