题目描述
解法
- split函数之后再反转列表
class Solution:
def reverseWords(self, s: str) -> str:
str_list = s.split()
str_list = str_list[::-1]
return ' '.join(str_list)
- 倒着遍历该str
设置两个指针,一个指向单词的开头,另一个指向单词的末尾
class Solution:
def reverseWords(self, s: str) -> str:
res = []
i = len(s)-1
j = len(s)-1
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
return ' '.join(res)