billryan / algorithm-exercise

Data Structure and Algorithm notes. 数据结构与算法/leetcode/lintcode题解/
https://algorithm.yuanbin.me
3.44k stars 892 forks source link

使python code维持总的时间复杂度为 O(n), 空间复杂度为 O(1) #75

Closed yehjames closed 8 years ago

yehjames commented 8 years ago

使python code维持总的时间复杂度为 O(n), 空间复杂度为 O(1)

billryan commented 8 years ago

空间复杂度仍为 O(n), Python 中的 str 为 immutable 的。测试程序如下:

def rotateString(A, offset):
    if A is None or len(A) == 0:
        return A

    offset %= len(A)
    A = A[len(A) - offset:] + A[:len(A) - offset]

    return A

str_raw = "immutable"
str_test = str_raw
str_rotate = rotateString(str_raw, 16)
print("str_raw: " + str_raw)
print("str_rotate: " + str_rotate)
print("str_test: " + str_test)

你的解法是最为简单直观的,但是和这道题的本意(三步翻转法)有点相悖。

yehjames commented 8 years ago

了解! Thanks!