7-line Python solution, 104ms


  • 1
    K

    The key is period 2 * (nRows - 1) and ascending + descending index ascDesIndex.

    def convert(self, s, nRows):
        if not s or nRows == 1: return s
        i, lenS, res, ascDesIndex = 0, len(s), ['' for j in range(nRows)], range(nRows - 1) + range(nRows - 1, 0, -1)
        while True:
            for j in ascDesIndex:
                if i >= lenS: return ''.join(res)
                res[j] += s[i]
                i += 1

Log in to reply
 

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