Java AC Easy Solution

  • 0
        public String reverseWords(String s) {
            String[] parts = s.split(" ");
            StringBuilder sb = new StringBuilder();
            for (int i = parts.length - 1; i >= 0; i--) {
                if (parts[i].length() == 0 || parts[i].equals(" ")) continue;
                sb.append(" ");
            return sb.toString().trim();

  • 0

    I don't think you need the check for whether or not a token in parts is a space, because splitting on space means that all spaces are either not present or represented by an empty string in the resulting token array. Correct me if I'm wrong?

Log in to reply

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