題目描述:
給定一個字符串和一個偏移量,根據偏移量旋轉字符串(從左向右旋轉)
樣例
對於字符串 "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)