コード例 #1
0
def check_tags(doc):
    s = Stack()
    tags = Stack()
    i = 0
    stub = ""
    which = None
    balanced = True
    while balanced and i < len(doc):
        if doc[i] == "<":
            if s.is_empty():
                s.push("<")
                if doc[i+1] == "/":
                    which = "close"
                else:
                    which = "open"
            else:
                balanced = False
        if not s.is_empty():
            if doc[i] == ">":
                s.pop()
                if which == "open"
                    tags.append(stub)
                    stub = ""
                elif which == "close":
                    last = tags.pop()
                    if stub != last:
                        balanced = False
                which = None
                stub = ""
            else:
                stub += doc[i]
        i += 1
    if balanced and s.is_empty() and tags.is_empty():
        return True
    return False