原题链接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)
网友评论