题目:汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
牛客网:链接
LeetCode同题:LeetCode189:Rotate Array
剑指offer这道题是默认K比数组长度小的,测试用例比较少。
字符串可以直接用下标取出字符。
把字符串分段相加。(最简单)
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
return s[n:] + s[:n]
还有一种思路。对原字符串进行扩充两倍,在这个基础上直接从要反转的地方取就可以,相当于前n个字符串翻转。
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
if not s:
return ''
length = len(s)
s += s
return s[n:length + n]
if __name__ == '__main__':
a = Solution()
print(a.LeftRotateString('abcdefg', 2))
常规做法
左旋转字符串:
(1) 先将左边 n个字符串进行翻转
(2)再将右边剩余字符串进行翻转
(3)最后将整个字符串进行翻转
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
if not s or n < 0 or n > len(s):
return ''
s = list(s)
frontList = self.Reverse(s[:n])
behindList = self.Reverse(s[n:])
resultStr = self.Reverse(frontList+behindList)
return ''.join(resultStr)
def Reverse(self, array):
if not array or len(array) == 1:
return array
startIndex = 0
endIndex = len(array) - 1
while startIndex < endIndex:
array[startIndex], array[endIndex] = array[endIndex], array[startIndex]
startIndex += 1
endIndex -= 1
return array
右旋转字符串:
(1) 先将整个字符串进行翻转
(2)再将左边 n个字符串进行翻转
(3)再将右边剩余字符串进行翻转