leetcode151. Reverse Words in a String

原题链接https://leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"
Example 2:

Input: " hello world! "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:

Input: "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

将原来字符串中各个单词单独反转,然后拼在一起,再一起反转。
注意两边和中间的空格,原字符串中间可能有好几个空格,但是反转后只有一个,两边的空格都要去掉。

class Solution:
    def reverseWords(self, s: str) -> str:
        if not s:
            return s
        def rever(word):
            return word[::-1]
        
        s = s.strip().split(" ")
        res = []
        for word in s:
            if word:
                res.append(rever(word))
        res = " ".join(res)
        return rever(res)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。