其他分享
首页 > 其他分享> > 第六题 Z字走法

第六题 Z字走法

作者:互联网

我和答案第一种解法是很相似的  但是时间 和空间都被大部分人击败了。

 

思路就是用一个标记  为0就竖着走 为1就斜着走 把二维数组填满 

我觉得难点在于PHYTON如何创建一个二维数组  而且是不定长的  

最后想出了竖着来  append的方法

不过这样好像时间复杂度爆炸了

def convert(s, numRows):
    """
    :type s: str
    :type numRows: int
    :rtype: str
    """
    rel = ''     #创建记录结果的字符串
    strlist = [[0]*numRows]  #根据python习惯  我觉得创建一个竖起来的数组更好操作一点。
    count = 0
    row = 0
    col = 0       #标记当前填写的行列
    flag = 0    #标记这次填写是填竖着的还是填斜着的。
    if numRows == 1 :
        return s
    for i in s:
        if flag == 0:
            strlist[row][col] = i
            col += 1
            if col == numRows-1 :
                flag = 1
        elif flag == 1:
            strlist.append([0]*numRows)
            strlist[row][col] = i
            row += 1
            col -= 1
            if col == 0:
                flag = 0
    for col in range(numRows):
        for each in strlist:
            if each[col] != 0:
                rel += each[col]

    return (rel)

 

标签:走法,第六,numRows,flag,rel,strlist,col,row
来源: https://www.cnblogs.com/xiaoli1996/p/15078816.html