My Accept Answer of Python with one line


  • 20
    L

    My Python code using the function of array and string. Both time and memory is O(n).

    class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        return " ".join(s.strip().split()[::-1])

  • 4
    J

    strip() can be removed since split() will handle beginning and ending spaces. I tried on python console and resubmitted, the answer is also accepted


  • 0
    L

    yeah, you are right. thank you.


  • 0
    T

    Oh, I forgot to use join(), so my code is more difficult, thank you~


  • 2
    C

    That's what I come up with when I see the clarification, trimming the extra space makes this really trivial in Python. Since string in Python is immutable, it won't make sense to ask a in-place solution, but a harder problem (possibly follow up) would be without removing the extra spaces and with just one pass of the string.


  • 2

    Thx for your solution.
    I saw some people who used reverse and I want add a comment that, [::-1] the the best and the fastest way to reverse a list.


  • 0
    D

    @lee215 Hey, for me reverse() was faster than slicing. I am not sure of the reason though.
    80% faster than other python submissions
    def reverseWords(self, s):
    l = s.strip().split()
    l.reverse()
    r = " ".join(l)
    return r

    65% faster than other python submissions
    def reverseWords(self, s):
    l = s.strip().split()
    a = l[::-1]
    r = " ".join(a)
    return r

        return r

  • 0
    Q

    strip() is no need


  • 1
    return ' '.join(reversed(s.split()))
    

Log in to reply
 

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