[LeetCode By Python] 6. ZigZag C

2016-06-28  本文已影响190人  乐乐可爱睡觉

一、题目

ZigZag Conversion

二、解题

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

三、尝试与结果

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

上一篇下一篇

猜你喜欢

热点阅读