Zigzag Conversion

题目描述

解题方法

Solution

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1 or numRows >= len(s):
            return s

        zigzag = [[] for i in range(numRows)]
        cur_row = 0
        step = 1
        for c in s:
            zigzag[cur_row].append(c)
            if cur_row == numRows - 1:
                step = -1
            elif cur_row == 0:
                step = 1
            cur_row += step
        result = ""
        for r in zigzag:
            result += "".join(r)

        return result

Reference