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


  • 0
    W

    class Solution(object):
    def isValidSerialization(self, preorder):
    """
    :type preorder: str
    :rtype: bool
    """
    if preorder is None:
    return False

        tmp = preorder.split(",")
        print "tmp = ", tmp
    
        string = ""
        for c in tmp:
            if c != "#":
                string = string + "1"
            else:
                string = string + "#"
    
        # string = preorder.replace(",", "")
        print "string = ", string
    
        lenS = len(string)
        print "lenS = ", lenS
    
        if "#,##" in string:
            return False
    
        while (len(string) > 0):
    
            if "##" not in string:
                break
    
            idx = string.index("##")
            if idx < 1:
                return False
    
            # print "idx = ", idx
            string = string[0:idx - 1] + "#" + string[idx + 2:]
            # string[idx-1] = '#'
            # print "after remove, string = ", string
    
        if string == "#":
            return True
        else:
            return False

Log in to reply
 

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