ZigZag Conversion
这个题也是一类对角线移动的特殊问题,具体到这道题,需要发现竖直移动和对角线移动时可以分为奇偶数轮,且对角线移动时行数是递减的,如此可以设定一个行数为numRows的矩阵,每次随着cursor的移动通过divmod函数就可以判断是在直线移动还是斜线移动,以及当前字符应该在哪一行了,下面是代码,个人觉得很简洁清晰了
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
n = len(s)
ref = [[] for _ in range(numRows)]
cur = 0
while cur < n:
mode, rem = divmod(cur, numRows - 1)
if mode % 2 == 0:
ref[rem].append(s[cur])
else:
ref[numRows - 1 - rem].append(s[cur])
cur += 1
return ''.join(reduce(lambda x, y : x + y, ref))