- 直接split。
class Solution:
def ReverseSentence(self , str: str) -> str:
a = str.split()
a = a[::-1]
return ' '.join(a)
- 使用re模块匹配正则表达式。适用范围更普遍啦。
import re
class Solution:
def ReverseSentence(self , str: str) -> str:
datepat = re.compile(r'\S+')
return ' '.join(datepat.findall(str)[::-1])
- 反向循环搜索空格,获得单词切片,加入列表
class Solution:
def ReverseSentence(self , str: str) -> str:
s = str.strip() # 删除首尾空格
i = j = len(s) - 1
res = []
while i >= 0:
while i >= 0 and s[i] != ' ': i -= 1 # 搜索首个空格
res.append(s[i + 1: j + 1]) # 添加单词
while s[i] == ' ': i -= 1 # 跳过单词间空格
j = i # j 指向下个单词的尾字符
return ' '.join(res) # 拼接并返回