[LeetCode]#557. Reverse Words in a String III
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:
- Use .split(“ “) to separate input based on “ “
- tmp=[“ let’s”, “take”, “leetCode”, “contest”]
- Use for loop ans=ans+tmp[i][::-1]+” “
- the last loop ans=ans+tmp[i][::-1]
- 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: