length = len(s) if length == 0: return"" i = 0# 用于遍历s begin = 0# 单词开始的位置 cur = 0# 遍历过程中,翻转后的字符串保存的位置 while i < length: if s[i] == " ": i += 1 continue begin = i while i < length: i += 1 if i >= length or s[i] == " ": s[cur:cur+(i-begin)] = self.reverse(s[begin:i]) cur += i-begin if cur < length: s[cur] = " " cur += 1 break if cur != 0and s[cur-1] == " ": cur -= 1 s = s[0:cur] return"".join(self.reverse(s)) defreverse(self, s): for k inrange(int(len(s)/2)): t = s[k] s[k] = s[len(s)-1-k] s[len(s)-1-k] = t return s