Java solution using stack


  • 0
    A
        public String reverseVowels(String s) {
            Stack<Character> vowels = new Stack<>();
            for(char c: s.toCharArray())
            {
                if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='A' || c=='E' || c=='I' || c=='O' || c=='U')
                    vowels.push(c);
            }
            
            StringBuilder result = new StringBuilder();
            for(char c : s.toCharArray()){
                if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u'|| c=='A' || c=='E' || c=='I' || c=='O' || c=='U')
    		result.append(vowels.pop());
                else
                   result.append(c);
            }
            return result.toString();
        }
    }
    

  • 0
    V

    @ani13492 I wrote the same code but with String for creating the final string like this - String s = s + poppedChar; but the time limit was being exceeded. Doing this using a StringBuilder, like in your code, seemed to fix the problem.

    Could anyone shed some light on whats the performance difference?


Log in to reply
 

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