频道栏目
首页 > 资讯 > Python > 正文

Python:Reverse Words in a String III题解

18-01-18        来源:[db:作者]  
收藏   我要投稿

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.

思路:

这里思路已经给的很明显了,因为Python字符串是不可改变的,所以只有利用单词之间的空格将句子分解成逐个的单词,然后在挨个单词取反,最后再用单个空格接再一起。

我的代码:

class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        word_list=s.split(' ')
        output=[]
        for word in word_list:
            reverse_word = word[::-1]
            output.append(reverse_word)
        return ' '.join(output)

同样的思路,一条语句就可以:

class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        return ' '.join([w[::-1] for w in s.split()])
<
相关TAG标签
上一篇:python生成器的理解
下一篇:算法系列15天速成——第三天 七大经典排序【下】
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站