My 10-line Java code that beats 73% of the submissions


  • 10

    Here is my concise and fast code that beats 73% of Java submissions.

    I scan from the end to make the concatenation logic clear and use StringBuilder to make the String concatenation faster. I also use trim when returning the results to avoid boundary checking.

    Hope it helps.

    public static String reverseWords(String s) {
        StringBuilder res = new StringBuilder();
        for (int start = s.length() - 1; start >= 0; start--) {
            if (s.charAt(start) == ' ') continue;
            int end = start;
            while (start >= 0 && s.charAt(start) != ' ') start--;
            res.append(s.substring(start + 1, end + 1)).append(" ");
        }
        return res.toString().trim();
    }

  • 0
    O

    clean answer. What do you mean by avoiding boundary checking?


  • 0
    W

    get rid of the leading and trailing spaces after append " " in the loop


  • 0
    C

    It is not working when the length of s is 1.


  • 0
    A

    @annieqt This solution takes O(N) time and O(N) space


  • 1

    Very clean! Thanks for sharing!


Log in to reply
 

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