A straightforward Python solution


  • 3
    D
    def convert(s, nRows):
        if nRows == 1:
            return s
        down = True
        strings = [""] * nRows
        # go through the string and append letters one by one
        lpos = 0
        for letter in s:
            strings[lpos] += letter
            if lpos == nRows - 1:
                lpos -= 1
                down = False
            elif lpos == 0:
                lpos = 1
                down = True
            elif down:
                lpos += 1
            else:
                lpos -= 1
        return "".join(strings)
    

    The idea is very simple: how do you as a human solve this problem? By going through the letters and following the zigzag pattern. So I'm keeping two extra variables: one boolean down, to see whether I'm going up or down, and one counter lpos, which I'm changing manually. Example: if nRows = 5, then lpos iterates through 0 1 2 3 4 3 2 1 0 1 2 3 4 3 2... etc. Like a zigzag!


Log in to reply
 

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