数组循环移位

字符串或数组的翻转,比如输入’hello’, return ‘olleh’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
slist = list(s)
def reverse(str1,index1,index2):
while index1 < index2:
str1[index1],str1[index2]=str1[index2],str1[index1]
index1 += 1
index2 -= 1
reverse(slist,0,len(slist)-1)
return ''.join(slist)

如果要求把字符串或数组向左或右移动k位,也可以通过reverse的方法做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def reverseString(self, s,k):
"""
:type s: str
:rtype: str
"""
slist = list(s)
N = len(s)
k %= N
def reverse(str1,index1,index2):
while index1 < index2:
str1[index1],str1[index2]=str1[index2],str1[index1]
index1 += 1
index2 -= 1
reverse(slist,0,N-k-1)
reverse(slist,N-k,N-1)
reverse(slist,0,N-1)
return ''.join(slist)