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.
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.
def reverseWords(self, s):
:type s: str
b = ''
a = s.split()
for i in a:
b = b + i[::-1] + ' '
b = b[:-1]
The solution is very simple with readable code, there are also some tricks we might use.
- 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