左旋转字符串python实现

原帖地址:http://blog.csdn.net/v_JULY_v/article/details/6322882


在这里贴上自己写的python代码实现,具体算法讲解请转到原帖


'''
Created on 2012-2-27

@author: [email protected]
'''

def rightshift1(arr,n,k):
    arr2 = list(arr)
    while k>0:
        t = arr2[n-1]
        j = n-1
        while j>0: 
            arr2[j] = arr2[j-1]
            j = j-1
        
        arr2[0] = t
        k = k-1

    return ''.join(arr2)

def rightshift2(arr,n,k):
    arr2 = list(arr)
    k = k%n
    while k>0:
        t = arr2[n-1]
        j = n-1
        while j>0: 
            arr2[j] = arr2[j-1]
            j = j-1
        
        arr2[0] = t
        k = k-1

    return ''.join(arr2)

def reverse(arr, start, end):
    arrs = list(arr)
    while start < end:
        
        temp = arrs[end]
        arrs[end] = arrs[start]
        arrs[start] = temp
        start += 1
        end -= 1
    
    return ''.join(arrs)

def rightshift3(arr,n,k):
    k %= n
    arr1 = reverse(arr,0,n-k-1)
    arr2 = reverse(arr1,n-k,n-1)
    arr3 = reverse(arr2,0,n-1)
    
    return arr3

def leftshift3(arr,n,k):
    k %= n
    return rightshift3(arr,n,n-k)
    


if __name__ == "__main__":
    s = 'abcd1234'
    print s
    print rightshift1(s,8,2)
    print rightshift2(s,8,18)
    print rightshift3(s,8,2)
    print leftshift3(s,8,2)


你可能感兴趣的:(算法,python)