zoukankan      html  css  js  c++  java
  • 基本数据结构之括号匹配-基于栈的实现

    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("([{)]}"))
    
  • 相关阅读:
    杂谈
    MD语法
    1034 有理数四则运算(20 分)
    1033 旧键盘打字(20 分)
    1032 挖掘机技术哪家强(20 分)
    1031 查验身份证(15 分)
    1030 完美数列(25 分)
    1029 旧键盘(20 分)
    1028 人口普查(20 分)
    1027 打印沙漏(20 分)
  • 原文地址:https://www.cnblogs.com/wsilj/p/12741410.html
Copyright © 2011-2022 走看看