My Simple and Easy understanding Python solution

  • 0

    I use 0 to represent '2', since this problem only need to add 1s. I think that can make things easier.

    class Solution(object):
        def magicalString(self, n):
            :type n: int
            :rtype: int
            # define the start situation, i is used to remember the index of s2, which is going to generate new element
            s1, s2, i = [1,0,0], [1,0,0], 2
            while len(s1)<n:
                # when s2[j] is 1, that means only needs to plus one element in s, else plus two
                new = ([0] if s1[-1] else [1]) if s2[i] else ([0, 0] if s1[-1] else [1, 1])
                # no matter s1 appends what, the same item will append to s2
                s1 += new
                s2 += new
                i += 1
            return sum(s1[:n])

    Learn from @realisking 's idea in his pretty smart solution,
    my idea can be revised more neat as following:

    class Solution(object):
        def magicalString(self, n):
            s, i = [1,0,0], 2
            while len(s) < n:
                s += [1-s[-1]] * (2-s[i])
                i += 1
            return sum(s[:n])

Log in to reply

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