题目描述
解答:
1. 库函数
class Solution:
def reverseWords(self, s: str) -> str:
l = s.split()[::-1]
return " ".join(l)
缺点:过于暴力,无法体现思路
2. 双指针
class Solution:
def reverseWords(self, s: str) -> str:
if not s:
return ""
l = r = 0
record = []
while r < len(s) + 1:
if r == len(s):
if s[r-1] != " ":
record.append(s[l:r])
break
if s[r] == " " and l == r:
l += 1
r += 1
elif s[r] == " " and l != r:
record.append(s[l:r])
l = r
else:
r += 1
return " ".join(record[::-1])
3. 反向搜索+双指针
class Solution:
def reverseWords(self, s: str) -> str:
i = j = len(s) - 1
res = []
while i >= 0:
while i >= 0 and s[i] != ' ': i -= 1
if s[i + 1: j + 1]:
res.append(s[i + 1: j + 1]) # 添加单词
while i >= 0 and s[i] == ' ': i -= 1 # 跳过单词间空格
j = i # j 指向下个单词的尾字符
print(i)
print(res)
return ' '.join(res) # 拼接并返回