Python solution using takewhile


  • -1
    Y
    def countAndSay(self, n):
        from itertools import takewhile, islice
        def generate_next(seq):
            i, result = 0, []
            while i < len(seq):
                for j, d in enumerate(takewhile(lambda x: x == seq[i], seq[i:])):
                    continue
                i += j + 1
                result += [str(j+1), d]
            return ''.join(result)
        def generate():
            cur = '1'
            while True:
                yield cur
                cur = generate_next(cur)
        return next(islice(generate(), n-1, None))

  • 0
    S
    This post is deleted!

Log in to reply
 

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