[leetcode] 6. ZigZag Conversion

 

Submission Detail

1158 / 1158 test cases passed.
Status: 

Accepted

Runtime: 76 ms
Memory Usage: 13.4 MB
Submitted: 2 hours, 17 minutes ago

 

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        lengthS = len(s)
        #0
        if lengthS <= 1 or numRows <= 1:
            return s
        #normal
        list = [[] for x in range(numRows)]
        divide = numRows + (numRows -2) # without first row and last row
        for index in range(lengthS):
            remainder = index %  divide
            if remainder < numRows: #the long cloume
                list[index % divide ].append(s[index])
            else:
                list[divide - remainder ].append(s[index])
        str =""
        for i in range(len(list)):
            str = str  + "".join(list[i])
        return (str)

 

 

 

挺简单的 注意余数不要大于数组数就没问题了

抄一个56ms的:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        strings = [''] * numRows
        direction = 1
        row_num = 0
        for x in s:
            strings[row_num] += x
            row_num += direction
            if row_num == numRows:
                row_num = numRows - 2
                direction = -1
            if row_num == -1:
                row_num = 1
                direction = 1
        return ''.join(strings)

 

posted @ 2019-04-29 14:12  夜歌乘年少  阅读(203)  评论(0编辑  收藏  举报