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.

题目分析及思路

题目给出一个字符串,要求将每个词中的字母顺序颠倒,但仍旧保留空格和原先的词序。可以用.split()方法将词分开并遍历,最后倒序并组成新的字符串。

python代码

class Solution:

    def reverseWords(self, s: 'str') -> 'str':

        s = s.split()

        res = ''

        for i in s:

            res += i[::-1]

            res += ' '

        return res.strip()

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10364160.html