[LeetCode By Python] 6. ZigZag Conversion

一、题目

[LeetCode By Python] 6. ZigZag Conversion_第1张图片
ZigZag Conversion

二、解题

按照Z字形状来重新遍历字符串(看上去是N字吧~)

  • 思路是做了一个二维数组,然后按照一定的规律变化下标(使用flag来判断当前应该是向下还是向上),把字符串的数字填入到二维数组中去。
  • 最后遍历一下整个二维数组即可。

三、尝试与结果

class Solution(object):
    def convert(self, s, numRows):
        if s == "" or numRows == 0 or numRows == 1:
            return s
        resultList = [[] for i in range(numRows)]
        row = numRows - 1
        ri = 0
        ci = 0
        num = 0
        flag = 0 # flag 0 for down,1 for up
        while num < len(s):
            resultList[ri].append(s[num])
            if flag == 1:
                ci = ci + 1
                ri = ri - 1
            elif flag == 0:
                ri = ri + 1
            if ri == 0 or ri == numRows - 1:
                flag = flag ^ 1
            num = num + 1

        result = ""
        for listi in resultList:
            for j in listi:
                result += str(j)
        return result

结果:AC

你可能感兴趣的:([LeetCode By Python] 6. ZigZag Conversion)