基本数据结构之括号匹配-基于栈的实现

from stack import Stack


def parChecker1(symbolString):
    """
    # 1. 创建一个空栈,默认标记为匹配成功
    # 2. 从左到右依次取括号
    # 3. 如果是"(",加入栈顶,如果是")",看栈是否为空,为空则匹配失败,否则pop栈顶
    # 4. 最后检查栈是否为空以及标记符号是否为True,为空则匹配成功,反之失败
    :param symbolString:
    :return:
    """
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        if symbolString[index] == "(":
            s.push("(")
        else:
            if s.isEmpty():
                balanced = False
            else:
                s.pop()
        index += 1
    if balanced and s.isEmpty():
        balanced = True
    else:
        balanced = False
    return balanced

print(parChecker1(""))

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        if symbolString[index] in "([{":
            s.push(symbolString[index])
        else:
            if s.isEmpty():
                balanced
            else:
                top = s.pop()
                if not matches(top, symbolString[index]):
                    balanced = False
        index += 1
    if balanced and s.isEmpty():
        return True
    else:
        return False

def matches(open, close):
    opens = "([{"
    closers = ")]}"
    return opens.index(open) == closers.index(close)

print(parChecker("{{([][])}()}"))
print(parChecker("[{()]"))
print(parChecker("([{)]}"))
原文地址:https://www.cnblogs.com/wsilj/p/12741410.html