Fast Java Solution 5ms / Beat 78%


  • 0
    P

    public String reverseVowels(String s) {

        char[] stringToCharacterArray = s.toCharArray() ;
        String vowels = "aeiouAEIOU";
        int head = 0 ;
        int tail = s.length() - 1 ;
        
        while(head < tail ) {
        
            boolean foundVowel = false ;
            
            if(vowels.indexOf(stringToCharacterArray[head]) != -1) 
            {
                
              // Loop from second pointer(tail) till it finds Vowel    
              while(foundVowel == false) {
                   if(vowels.indexOf(stringToCharacterArray[tail]) == -1) {
                       tail-- ;
                    } else {
                        foundVowel = true ;
                        break ;
                    }
               }
               
              // Swap
              char temp = stringToCharacterArray[head] ;
              stringToCharacterArray[head] = stringToCharacterArray[tail] ;
              stringToCharacterArray[tail] = temp ;
               
              head++ ;
              tail-- ;
                
            } else {
                head++ ;
            }
        }
     
        return new String(stringToCharacterArray) ;
        
    }

Log in to reply
 

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