Java Two Pointer Solution 7ms


  • 0
    Q
    public class Solution {
        public String reverseVowels(String s) {
            char[] chars = s.toCharArray();
            int i = 0, j = chars.length-1;
            while(j > i){
                if(isVowel(s.charAt(i))){
                    while(!isVowel(s.charAt(j))){
                        j--;
                    }
                        
                    if(j > i){
                        chars[j] = s.charAt(i);
                        chars[i] = s.charAt(j);
                        j--;
                    }
                }
                i++;
            }
            return new String(chars);
        }
        
        public boolean isVowel(Character c){
            if(Character.toLowerCase(c) == 'a' ||
            Character.toLowerCase(c) == 'e'||
            Character.toLowerCase(c) == 'i'||
            Character.toLowerCase(c) == 'o'||
            Character.toLowerCase(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.