美文网首页
leetcode151. Reverse Words in a

leetcode151. Reverse Words in a

作者: 就是果味熊 | 来源:发表于2020-07-25 17:08 被阅读0次

原题链接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)

相关文章

网友评论

      本文标题:leetcode151. Reverse Words in a

      本文链接:https://www.haomeiwen.com/subject/csdmlktx.html