Great time to use a Stack


  • 0
    E
     public String reverseVowels(String s) {
           if(s.isEmpty() || s == null) return s;
           
           HashSet<Character> vowels = new HashSet<>();
           Stack<Character> stack = new Stack<>();
           vowels.add('a');
           vowels.add('e');
           vowels.add('i');
           vowels.add('o');
           vowels.add('u');
           
           vowels.add('A');
           vowels.add('E');
           vowels.add('I');
           vowels.add('O');
           vowels.add('U');
           
           char arr[] = s.toCharArray();
           for(char c : arr){
               if(vowels.contains(c))
                 stack.push(c);
           }
          
           for(int i = 0; i < arr.length; i++){
               if(vowels.contains(arr[i]))
                 arr[i] = stack.pop();
           }
           
           return new String(arr);
        }

Log in to reply
 

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