給定一個(gè)字符串,逐個(gè)翻轉(zhuǎn)字符串中的每個(gè)單詞。
說明:
無空格字符構(gòu)成一個(gè) 單詞 。
輸入字符串可以在前面或者后面包含多余的空格,但是反轉(zhuǎn)后的字符不能包括。
如果兩個(gè)單詞間有多余的空格,將反轉(zhuǎn)后單詞間的空格減少到只含一個(gè)。
示例 1:
輸入:“the sky is blue”
輸出:“blue is sky the”
示例 2:
輸入:" hello world! "
輸出:“world! hello”
解釋:輸入字符串可以在前面或者后面包含多余的空格,但是反轉(zhuǎn)后的字符不能包括。
示例 3:
輸入:“a good example”
輸出:“example good a”
解釋:如果兩個(gè)單詞間有多余的空格,將反轉(zhuǎn)后單詞間的空格減少到只含一個(gè)。
示例 4:
輸入:s = " Bob Loves Alice "
輸出:“Alice Loves Bob”
示例 5:
輸入:s = “Alice does not even like bob”
輸出:“bob like even not does Alice”
思路1:
傳統(tǒng)思路:先使用strip()
函數(shù)將首尾空格去掉;特別注意,中間的空格可能不止一個(gè)。采用雙指針,從后遍歷字符串,遇到的第一個(gè)空格,回退一個(gè)到j(luò)的位置就會(huì)取出一個(gè)字符串。
![](/d/20211017/841fd0b3677d5146f61163f2bd351914.gif)
![](/d/20211017/d42afb16e5f8006cd5b907af08313e4b.gif)
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:
![](/d/20211017/54124edad5116ac7f2ecd2e0f5a77d52.gif)
class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
s = s.split()
s.reverse()
return ' '.join(s)
到此這篇關(guān)于python3翻轉(zhuǎn)字符串里的單詞點(diǎn)的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)python3翻轉(zhuǎn)字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python中實(shí)現(xiàn)字符串翻轉(zhuǎn)的方法
- 利用perl、python、php、shell、sed、awk、c 實(shí)現(xiàn)字符串的翻轉(zhuǎn)