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         
参考代码

 

转载于:https://www.cnblogs.com/lhppom/p/8508749.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值