leetcode Z字形變換

示例 1:python

輸入: s = "PAYPALISHIRING", numRows = 3
輸出: "PAHNAPLSIIGYIR"

示例 2:app

輸入: s = "PAYPALISHIRING", numRows = 4
輸出: "PINALSIGYAHRPI"
解釋:

P     I    N
A   L S  I G
Y A   H R
class Solution(object):
    def convert(self, s, numRows):
        if len(s)==0:
            return ""
        if len(s)<=numRows or numRows==1:
            return s
        result = []
        tmp_n = numRows
        while tmp_n > 0:
            tmp_n = tmp_n - 1
            result.append([])
        lt_mp=[]
        for i in range(1, numRows - 1):
            lt_mp.append(i)
        lt_mp.reverse()
        l = list(s)
        i = 0
        while i< len(l):
            row = 0
            while row <= (numRows - 1): #4
                if row + i < len(l):
                    result[row].append(l[i + row])
                    row = row + 1
                else:
                    row=numRows
            i = i + numRows
            if len(l)>=i+1:
                for j in lt_mp:
                    if i >= len(l):
                        continue
                    else:
                        result[j].append(l[i])
                        i = i + 1
        a=[]
        for i in result:
            a.extend(i)
        return(''.join(a))
相關文章
相關標籤/搜索