One line accepted python code

  • 7

    One line accepted python code, although that is no the interview goal.

    class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        return ' '.join(reversed(s.split()))

  • 1

    Came here to post this exact solution. You beat me to it.

    I think java and c++ people would call this cheating, but if I was interviewing somebody for a python job and they resorted to iterating through letters, I'd assume they didn't know Python very well.

  • 1

    Few chars shorter :

    ' '.join(s.split()[::-1])

  • 0

    and the one line javascript solution:

    return str.trim().split(/\s+/).reverse().join(" ");

Log in to reply

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