先转单词,再转句子。比较简单好理解的Python代码,以及后面相似的左旋转字符串的代码
本题
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
左旋转字符子串
def LeftRotateString(self, s, n): # write code here s = list(s) s[:n] = self.reverse(s[:n]) s[n:] = self.reverse(s[n:]) 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