题目描述:
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
样例
对于字符串 "abcdefg"
.
offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
挑战
在数组上原地旋转,使用O(1)的额外空间
题目分析:
题目原意是处理字符串,达到旋转字符串的要求,首先的思路是Python的字符串切片操作,以offset为界,然后再拼接
class Solution: # @param s: a list of char # @param offset: an integer # @return: nothing def rotateString(self, s, offset): # write you code here if not offset: return if not s: return n = len(s) offset = offset%n # offset可能大于N,取offset模n的余数 f = n - offset return s[f:n]+s[0:f]
结果,题目传入的是数组类型,需要直接处理原数组对象,而不是返回一个新的数组or字符串,so,更改如下:
class Solution: # @param s: a list of char # @param offset: an integer # @return: nothing def rotateString(self, s, offset): # write you code here if not offset: return if not s: return n = len(s) offset = offset%n for i in range(offset): t = s.pop() s.insert(0,t)