Easiest Java solution using Stack


  • 0
    S

    The idea is to parse the input string character by character from the beginning and push the characters onto a stack. Soon as we encounter a space character, start building a string popping characters off the stack. This retains the reverse order.

    Space characters go on the new string as they appear.

    The only thing to worry about is the last word. It will be skipped for pushing onto the new string because we were looking for space delimiter. We'll take care of it at the end.

    public static String reverseWords(String s) {
            Stack<Character> stack = new Stack<>();
            StringBuilder newString = new StringBuilder();
    
            for(int i=0; i<s.length(); i++) {
                if(s.charAt(i) == ' ') {
                    while(stack.size() > 0) {
                        newString.append(stack.pop());
                    }
    
                    newString.append(' ');
                }
    
                else {
                    stack.push(s.charAt(i));
                }
    
            }
    
            while(stack.size() > 0) {
                newString.append(stack.pop());
            }
    
            return newString.toString();
    }
    

Log in to reply
 

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