Two python code, straight forward use slice and neat use itertools


  • 6
    T
    class Solution:
    # @return a string
    def convert(self, s, n):
        res = [[] for _ in range(n)]
        i = 0
        try:
            while True:
                for r in res:
                    r.append(s[i])
                    i += 1
                for r in res[-2:0:-1]:
                    r.append(s[i])
                    i += 1
        except IndexError:
            return ''.join(''.join(r) for r in res)
    

    Here's a neat one

    class Solution:
    # @return a string
    def convert(self, s, n):
        idx = itertools.chain(range(n), range(n-2, 0, -1))
        res = [[] for _ in range(n)]
        for char, i in zip(s, itertools.cycle(idx)):
            res[i].append(char)
        return ''.join(''.join(r) for r in res)

  • 0
    N

    The slice one is pretty damn smart. Haven't really thought I could use slice that way. Using the iterloop ones makes me feel naughty. lol


Log in to reply
 

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