輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字符的順序不變。爲簡單起見,標點符號和普通字母一樣處理。例如輸入字符串"I am a student. “,則輸出"student. a am I”。
示例 1:
輸入: “the sky is blue”
輸出: “blue is sky the”
示例 2:
輸入: " hello world! "
輸出: “world! hello”
解釋: 輸入字符串可以在前面或者後面包含多餘的空格,但是反轉後的字符不能包括。
示例 3:
輸入: “a good example”
輸出: “example good a”
解釋: 如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。
說明:
無空格字符構成一個單詞。
輸入字符串可以在前面或者後面包含多餘的空格,但是反轉後的字符不能包括。
如果兩個單詞間有多餘的空格,將反轉後單詞間的空格減少到只含一個。
注意:本題與主站 151 題相同:https://leetcode-cn.com/problems/reverse-words-in-a-string/
注意:此題對比原題有改動
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路1:list反轉
將字符串先切割然後存入list,利用list反轉即可。
class Solution:
def reverseWords(self, s: str) -> str:
strlist = s.split(' ')
ans = []
for st in strlist:
if st != '' :
ans.append(st)
# return ' '.join(ans[::-1])
# return ' '.join(reversed(ans))
ans.reverse()
return ' '.join(ans)