Accepted Java Code 8 lines


  • 0

    I have used two StringBuilder's.

    public static String reverseWords(String s) {
            StringBuilder result = new StringBuilder();
            StringBuilder temp = new StringBuilder();
            for (String word : s.split(" ")) {
                temp.append(word.toCharArray()).reverse();
                result.append(temp).append(" ");
                temp.setLength(0);
            }
            return result.deleteCharAt(result.length() - 1).toString();
        }
    

    The temp StringBuilder reverses each individual word and appends it to the result and then clears itself to process the next word. And before we return the result, we delete the extra space at end.


Log in to reply
 

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