题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
原理:YX = (XTYT)T
# -*- coding:utf-8 -*-
class Solution:
def LefRotateString(self, s, n):
if not s:
return s
lens = len(s)
n %= lens
s = list(s) #python str是不可变的 list可变
i, j = 0, n - 1
while i < j:
t = s[i]
s[i] = s[j]
s[j] = t
i += 1
j -= 1
i, j = n, lens - 1
while i < j:
t = s[i]
s[i] = s[j]
s[j] = t
i += 1
j -= 1
i, j = 0, lens - 1
while i < j:
t = s[i]
s[i] = s[j]
s[j] = t
i += 1
j -= 1
return "".join(s)
方法二
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
return s[n:] + s[:n]