58扩展. 左旋转字符串
左旋转字符串
http://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec
- 左旋转字符串与此题类似,先翻转旋转的n位字符,再翻转其余的字符,最后翻转整个字符串,例如abcdefg左旋转两位:首先变为bacdefg,然后bagfedc,最后cdefgab为所求
class Solution:
def LeftRotateString(self, s, n):
# write code here
if not s or n == 0:
return s
n = n % len(s)
s = list(s)
first = self.reverse(s[:n])
last = self.reverse(s[n:])
return ''.join(self.reverse(first + last))
def reverse(self, s):
head = 0
end = len(s) - 1
while head < end:
s[head], s[end] = s[end], s[head]
head += 1
end -= 1
return s