Easiest way to think about it | Python Solution


  • 0
    S

    When the number of rows = 3, the string PAYPALISHIRING is converted to
    row 1 : P A H N
    row 2 : A P L S I I G
    row 3 : Y I R
    Since we are supposed to return PAHNAPLSIIGYIR, think about the letters and what rows they go to.

    P | A | Y | P | A | L | I | S | H | I | R | I | N | G 
    1 | 2 | 3 | 2 | 1 | 2 | 3 | 2 | 1 | 2 | 3 | 2 | 1 | 2
    

    Now if we can build a string by first picking those in row 1, then 2, and so on we have our required string.
    Say if the number of rows were 4, the situation would look like
    P A Y P A L I S H I R I N G
    1 2 3 4 3 2 1 2 3 4 3 2 1 2
    This leads us to the following solution

    def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            h = {}
            adding = True
            count = 1
            for i in range(len(s)):
                if count in h:
                    h[count].append(s[i])
                else:
                    h[count] = [s[i]]
    
                if count == numRows:
                    adding = False
                if count == 1:
                    adding = True
                if adding:
                    count+=1
                else:
                    count-=1
            return "".join([ch for sublist in h.values() for ch in sublist])
    

    where we just vary the range from 1 to numRows and assign each letter a row


Log in to reply
 

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