My 44 ms python solution

  • 0
    class Solution:
        # @param s, a string
        # @return a string
        def reverseWords(self, s):
            # Step 1 : split the given string into a list of words - with " " as the seperator
            s = s.split(" ")
            # Step 2 : filter out the white spaces in the list and reverse the list
            s = [element for element in s if element != ''][::-1]
            # Step 3 : join them and return 
            return ' '.join(s)

    Let me know if I can make this faster.

  • 0

    I am not sure whether can make it faster or not, but as you are using Python, you can reduce the code to 1 line:

    def reverseWords(self, s):
        return " ".join(s.split()[::-1])

Log in to reply

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