欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python:Reverse Words in a String III题解

程序员文章站 2022-05-03 19:32:36
557. Reverse Words in a String III Given a string, you need to reverse the order of chara...

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()])
<