分析:旋转字符串是反转字符串的扩展,如s=‘abcdefg’,k=2,要求为把s的左边两位旋转到最后位置:cdefgab
以下用了1、切片 2、双向队列两种方法
代码:
#左旋转字符串 #方法1:切片 s='abcdefg' print(s) k=2 l=s[k:]+s[0:k] print(l) print("---------------") #方法2:使用双端队列 from collections import deque s='abcdefg' d = deque(s) k=2 d.rotate(-k)#把队列前k个数扭转到右端 print(type(d)) print(d) l=''.join(d) print(l) print("---------------") #扩展双队列 s='abcdefg' d = deque(s) d.rotate()#默认是把最后一个移到最前面 print(d) d.rotate(2)#是把最后2个整体移到最前面 print(d) d.rotate(-1)#是把第1个移到最后面 print(d) d.rotate(-2)#是把前两个整体移到最后面 print(d) 输出结果:
abcdefg
cdefgab
---------------
<class 'collections.deque'>
deque(['c', 'd', 'e', 'f', 'g', 'a', 'b'])
cdefgab
---------------
deque(['g', 'a', 'b', 'c', 'd', 'e', 'f'])
deque(['e', 'f', 'g', 'a', 'b', 'c', 'd'])
deque(['f', 'g', 'a', 'b', 'c', 'd', 'e'])
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
Process finished with exit code 0