lintcode:旋轉字串
阿新 • • 發佈:2019-01-25
class Solution:
# @param s: a list of char
# @param offset: an integer
# @return: nothing
def rotateString(self, s, offset):
# write you code here
# 198ms
if not s:return s
n = len(s)
offset = offset % n
if not s:return s
for i in range(offset):
t = s.pop()
s.insert(0,t)
# 189ms 分別賦值
if not s:return s
n = len(s)
offset = offset % n
if not offset:return s
temp_pre = s[-offset:]
temp_las = s[0:n-offset]
m = len(temp_pre)
for i in range(len(temp_pre)):
s[i] = temp_pre[i]
for i in range(len(temp_pre), n):
s[i] = temp_las[i - m]
# 206ms 字串 * 2
if not s:return s
n = len(s)
offset = offset%n
if not offset:return s
temp = s*2
for i in range(n):
s[i] = temp[n-offset+i]
# 198ms 互換位置
if not s: return s
n = len(s)
offset = offset % n
if not offset:return s
s[0:n-offset], s[-offset:] = s[-offset:], s[0:n-offset]
# 226ms 三次反轉
if not s:return s
n = len(s)
offset = offset % n
if not offset:return s
s[0:n-offset] = reversed(s[0:n-offset])
s[-offset:] = reversed(s[-offset:])
s[::] = reversed(s)