A/C Python solution, easy to understand, beat 49.69%


  • 0
    W
    def magicalString(self, n):
        """
        :type n: int
        :rtype: int
        """
    
        """
        :type n: int
        :rtype: int
        """
        #print "n = ", n
    
        res = "122"
    
        for i in range(4, n+1):
            #print "i = ", i
            #print "res = ", res
            previousTwoCs = res[i-3:i-1]
            #print "previousTwoCs = ", previousTwoCs
    
            tailTwoCs = res[-2:]
            #print "tailTwoCs = ", tailTwoCs
    
            if previousTwoCs[1] == "2":
                if tailTwoCs[1] == "1":
                    res += ("22")
                elif tailTwoCs[1] == "2":
                    res += ("11")
    
            else:
                if tailTwoCs[1] == "1":
                    res += ("2")
                elif tailTwoCs[1] == "2":
                    res += ("1")
    
            #print "2 res = ", res
        #print "res = ", res[:n]
        #print "res[:n].count(1) = ", res[:n].count("1")
    
        return res[:n].count("1")

Log in to reply
 

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