My easy read python solution


  • 11
    B

    Consume the numRows is 5,we see the zigzag pattern like this:

    0        8
    1     7  9
    2   6   10
    3 5     11
    4       12...
    

    we can see the numbers 0~7 is a small pattern in here,if we divide 8 we can get same number in other small patterns.like
    0%8 = 0; 8%8 = 0
    1%8 = 1; 9%8 = 1
    so we can use this feature and filter them into rows we store.and this is my code:

    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            if numRows == 1: return s
            rows = [''] * numRows
            num = (numRows-1)*2
            for i, item in enumerate(s):
                if i % num >= numRows:
                    rows[(num - i % num) % numRows] += item
                else:
                    rows[i % num] += item
            return ''.join(rows)

  • 2
    L

    Really nice solution.
    Replace rows[(num - i % num) % numRows] += item with rows[(num - i % num)] += item.
    It would be better.


  • 0
    B

    you are right,thanks~


  • 0

    my similiar solution

    class Solution(object):
         def convert(self, s, numRows):
              n = numRows
              if n == 1: return s
              res = [''] * n 
              for i, e in enumerate(s):
                  res[i%(n-1) if i//(n-1)%2 == 0 else n-1-i%(n-1)] += e
              return ''.join(res)

Log in to reply
 

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