先转单词,再转句子。比较简单好理解的Python代码
class Solution: def ReverseSentence(self, s): # write code here wordstart = 0 s = list(s) for i in range(len(s)): if s[i]==' ': s[wordstart:i] =self.reverse(s[wordstart:i]) wordstart = i+1 s[wordstart:] = self.reverse(s[wordstart:]) s = self.reverse(s) return ''.join(s) def reverse(self, words): for i in range(len(words)>>1): words[i], words[-i-1] = words[-i-1],words[i] return words参考资料: