58-2左旋转字符串-python

题目:字符串左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请实现左旋转操作。

def reverse(arry,begin,end):
    while begin<end:
        arry[begin],arry[end] = arry[end],arry[begin]
        begin +=1
        end -=1

def left_rotate_string(s,n):
    s = list(s)
    ls = len(s)
    reverse(s,0,ls-1)
    reverse(s,0,ls-n-1)
    reverse(s,ls-n,ls-1)
    return ''.join(s)

  注:主要思路是采用3次旋转,第一次字符串全部旋转;第二次前半部分旋转,以指定的n为分界点,此时旋转一次后的分界点变为len(s)-n;第三次后面部分旋转。

猜你喜欢

转载自blog.csdn.net/wh672843916/article/details/105503763