My accpeted answer with Python


  • 0
    J
    class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        k = s.strip().split(" ")
        wordsList = []
        returnWords = ""
        for word in k[::-1]:
            if word != "" and word != " ":
                returnWords += word + " "
        return returnWords.strip()
    

    I want to use regular express at first, but it seems like the OJ does not allow.
    Is there any other more tidy solution?


  • 0
    Z

    Here's mine:

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

  • 0
    K
    This post is deleted!

  • 0
    K
    This post is deleted!

  • 0
    K
    This post is deleted!

  • 5
    K
    class Solution:
        # @param s, a string
        # @return a string
        def reverseWords(self, s):
            return ' '.join(s.split()[::-1])

  • 0
    J

    Nice code!
    I stupidly use s.split(' '), and this will return the empty string '' as elements in the result list.


  • 0
    L

    here is mine:

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

Log in to reply
 

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