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.
题意:给出一个字符串集,以空格符为分隔符相连,把字符串集每个元素即一个字符串相连的反转再以空格符为分隔符相连回来
想法:其实实现很粗暴就是先切割出来,然后单个reverse一下,再使用str.join(str_list)连接成目的字符串结果。这道题看到一个比较有意思的解法就是你先把整个字符串反转一遍,然后切割,最后再翻转一遍用空格连接,大家可以品上一品,还是挺有意思的,它的第一次翻转和第二次翻转的目的其实是不一样的。
1 class Solution(object): 2 def reverseWords(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 8 return ' '.join([st[::-1] for st in s.split(" ")]) 9 10