Table of Content
题目:
这个题我采用的是通过方向控制,来将字符串里的字符添加到构建的list中,在循环中的碰到最后一行或者第一行进行方向改变。需要考虑行数为 1 的特殊情况,这种情况下直接返回字符串。
参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
class Solution: def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ # no need to convert if numRows == 1: return(s) zlist = [] sc = "" n = numRows # create null list while n: zlist.append([]) n = n - 1 j = 0 for a in s: if j == 0: # direction change coverse = False zlist[j].append(a) if j + 1 < numRows: if coverse: j = j - 1 else: j = j + 1 else: j = j - 1 # direction change coverse = True # get the converted string for z in zlist: for t in z: sc = sc + t return(sc) |