JAVA - 4ms - beat 93.41 % - Two pointer + switch


  • 0
    N
    public class Solution {
        
        
        public String reverseVowels(String s) {
            if (s == null || s.length() <= 1) return s;
            
            char[] result = s.toCharArray();
            
            int begin = 0, end = s.length() - 1;
            
            while (begin != end){
                if (isVowels(result[begin])) {
                    char first = result[begin];
                    while (begin != end){
                        if (isVowels(result[end])) {
                            result[begin++] = result[end];
                            result[end] = first;
                            
                            if(begin == end) {
                                return new String(result);
                            } else {
                                end--;
                                break;
                            }
                            
                        } else {
                            end--;
                        }
                    }
                } else {
                    begin++;
                }
            }
            return new String(result);
        }
        
        private boolean isVowels(char c) {
            switch (c) {
                case 'a' : return true;
                case 'e' : return true;
                case 'i' : return true;
                case 'o' : return true;
                case 'u' : return true;
                case 'A' : return true;
                case 'E' : return true;
                case 'I' : return true;
                case 'O' : return true;
                case 'U' : return true;
                default : return false;
            }
        }
    }
    

Log in to reply
 

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