6 lines simple Python

  • 0

    Here I used word to store the characters in each row, and via (i // n) & 1 to determine the current direction to put every character into the right rows. When the result of current index i divided by (numRows - 1) is even, we are in the DOWN direction, and odd when we are in the UP direction.

    class Solution(object):
        def convert(self, s, numRows):
            :type s: str
            :type numRows: int
            :rtype: str
            if numRows == 1: return s
            words, n = [""] * numRows, numRows - 1
            for i, c in enumerate(s):
                idx = n - i % n if (i // n) & 1 else i % n
                words[idx] += c
            return "".join(words)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.