[LeetCode]#557. Reverse Words in a String III

Fatboy Slim
1 min readJun 8, 2020

Environment: Python 3.7

Key technique: .split , list

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"

Analysis:

  1. Use .split(“ “) to separate input based on “ “
  2. tmp=[“ let’s”, “take”, “leetCode”, “contest”]
  3. Use for loop ans=ans+tmp[i][::-1]+” “
  4. the last loop ans=ans+tmp[i][::-1]
  5. return ans

Solution:

class Solution:
def reverseWords(self, s):
tmp=s.split(" ")
ans=""
for i in range(len(tmp)):
if i==(len(tmp)-1):
ans=ans+tmp[i][::-1]
else:
ans=ans+tmp[i][::-1]+" "
return ans

Submissions:

--

--