Stack solution


  • 0
    U

    Pick each word into a stack, and append every elements poped from stack.

        public String reverseWords(String s) {
            Stack<StringBuilder> stk = new Stack<StringBuilder>();
            int len = s.length();
            StringBuilder word = new StringBuilder();
            StringBuilder rtn = new StringBuilder();
            for (int i = 0; i < len; ++i) {
                if (s.charAt(i) != ' ') word.append(s.charAt(i));
                else if (word.length() != 0) {
                        stk.push(word);
                        word = new StringBuilder();
                }
            }
            if (word.length() != 0) stk.push(word);
            while (!stk.isEmpty()) {
                rtn.append(stk.pop());
                rtn = (!stk.isEmpty()) ? rtn.append(" ") : rtn;
            }
            return rtn.toString();
        }
    

Log in to reply
 

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