給定一個字符串,逐個翻轉字符串中的每個單詞。
說明:
無空格字符構成一個 單詞 。
輸入字符串可以在前面或者后面包含多余的空格,但是反轉后的字符不能包括。
如果兩個單詞間有多余的空格,將反轉后單詞間的空格減少到只含一個。
示例 1:
輸入:“the sky is blue”
輸出:“blue is sky the”
示例 2:
輸入:" hello world! "
輸出:“world! hello”
解釋:輸入字符串可以在前面或者后面包含多余的空格,但是反轉后的字符不能包括。
示例 3:
輸入:“a good example”
輸出:“example good a”
解釋:如果兩個單詞間有多余的空格,將反轉后單詞間的空格減少到只含一個。
示例 4:
輸入:s = " Bob Loves Alice "
輸出:“Alice Loves Bob”
示例 5:
輸入:s = “Alice does not even like bob”
輸出:“bob like even not does Alice”
思路1:
傳統思路:先使用strip()
函數將首尾空格去掉;特別注意,中間的空格可能不止一個。采用雙指針,從后遍歷字符串,遇到的第一個空格,回退一個到j的位置就會取出一個字符串。


class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
i = len(s)-1
j = i+1
resverse = []
while i>=0:
while i >= 0 and s[i] != ' ': i -= 1
resverse.append(s[i + 1: j])
while s[i] == ' ': i -= 1
j = i+1
return ' '.join(resverse).strip()
思路2:

class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
s = s.split()
s.reverse()
return ' '.join(s)
到此這篇關于python3翻轉字符串里的單詞點的實現方法的文章就介紹到這了,更多相關python3翻轉字符串內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python中實現字符串翻轉的方法
- 利用perl、python、php、shell、sed、awk、c 實現字符串的翻轉