easy understand solution by python


  • 5
    T

    my python solution
    idea:

    0 _ _ _ _ _ 6     => 6,6,6...
    _ 1 _ _ _ 5 _ 7  => (6-2), (6-4), (6-2) ...
    _ _ 2 _ 4 _ _ _ 8 => (6-4), (6-2), (6-4) ...
    _ _ _ 3 _ _ _ _ _ 9 =>6,6,6,6
    
    class Solution(object):
        def convert(self, s, numRows):
            strLen = len(s)
            if numRows == 1 or strLen == 1 or strLen == 0:
                return s
    
            ans = ''
            l = 2 * (numRows - 1)
            for i in range(numRows):
                j = i
                r = i * 2
                while j < strLen:
                    ans += s[j]
                    # first and last
                    if i == 0 or i == numRows - 1:
                        j += l
                    else:
                        r = l - r
                        j += r
            return ans
    

Log in to reply
 

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