Leetcode: Reverse Words in a String

Reverse Words in a String



Similar Problems:


Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## Blog link: https://code.dennyzhang.com/reverse-words-in-a-string
## Basic Ideas:
##       the sky is blue
##       eulb si yks eht
##       blue is sky the
##
## Complexity: Time O(n), Space O(1)
class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = s[::-1]
        res = []
        for item in s.split(" "):
            if item == "":
                continue
            res.append(item[::-1])
        return ' '.join(res)
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.