题目描述:
题解一:
python库split自动去掉字符串首位和中间多余的空格
class Solution(object): def reverseWords(self, s): words = s.split() words.reverse() result = " " return result.join(words)
题解二:双指针
参考剑指 Offer 58 - I. 翻转单词顺序(双指针/python库函数) - Yelush - 博客园
1.首先去除s前后的空格,i j记录单词的左右边界,初始化i,j=len(s)-1
class Solution(object): def reverseWords(self, s): s = s.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 = i-1 j = i return " ".join(res)