方法:利用bucket sort
想了几天没想出来,想得到一个特定模式,但没找到,其实用bucket的原理很容易解决。Z字形的字符串按照顺序放在bucket里,然后把bucket连接起来,考虑边界条件如何放置,需要用到一个flip变量,控制如何放。总是忘记边界条件, 若是一行没有必要flip
'''
time: O(n+k < n + n) = O(n), n is number of char in str and k is number of rows
space: O(n)
'''
# numRows >= len(s) does not influence res, but saves space
if numRows == 1 or numRows >= len(s):
return s
flip = -1
row = 0
res = [[] for i in range(numRows)]
# iterate through string
for c in s:
res[row].append(c)
if row == 0 or row == numRows - 1:
flip *= -1
row += flip
# consolidate res
for i in range(len(res)):
res[i] = "".join(res[i])
return "".join(res)