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("([{)]}"))
    
  • 相关阅读:
    简单小过一个crc
    BUUCTF-RE-babymips
    为IDA插件findcrypt添加更多规则
    2020网鼎杯第一场青龙组re部分wp
    HexionCTF2020 部分wp
    TGhack2020 re&misc
    java反射总结
    BUUCTF-RE-CrackMe
    青年大学习直接出图片的软件出了bug,用frida干他
    小玩具Teensy
  • 原文地址:https://www.cnblogs.com/wsilj/p/12741410.html
Copyright © 2011-2022 走看看