[Daily Leetcode]557. Reverse Words in a String III


Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.


class Solution(object):
    def reverseWords(self, s):
        :type s: str
        :rtype: str

        b = ''
        a = s.split()
        for i in a:
            b = b + i[::-1] + ' '
        b = b[:-1]
        return b


The solution is very simple with readable code, there are also some tricks we might use.

  1. How to reverse a string?

By using the s[ start : end : step ], if step = -1, then the string will be counted from the end to the first

2. How to cut the last character out of the string?

By using s[ : – 1], here -1 means the last character of the string

Leave a Reply

Your email address will not be published. Required fields are marked *