栈:Stack

作者: lizg | 来源:发表于2022-04-03 20:59 被阅读0次

    1.action

    Stack() :初始化空栈
    push(item) : 栈顶插入
    pop() :栈顶弹出
    peek() :返回栈顶元素
    isEmpty() :判断是否为空
    size() :栈元素数
    

    2.code of python

    class Stack:
        def __init__(self):
            self.items = []
    
        def isEmpty(self):
            return self.items == []
        
        def push(self, item):
            return self.items.append(item)
        
        def pop(self):
            return self.items.pop()
        
        def peek(self):
            return self.items[len(self.items)-1]
        
        def size(self):
            return len(self.items)
    

    3.应用:括号匹配

    from stack import Stack
    
    def parChecker(symbolString):
        s = Stack()
        index = 0
        balanced = True
        while index < len(symbolString) and balanced:
            symbol = symbolString[index]
            if symbol == "(":
                s.push(symbol)
            else:
                if s.isEmpty():
                    balanced = False
                else:
                    s.pop()
            index += 1
        if balanced and s.isEmpty():
            return True
        else:
            return False
    
    print(parChecker("()()(())"))
    print(parChecker("(((())"))
    

    相关文章

      网友评论

        本文标题:栈:Stack

        本文链接:https://www.haomeiwen.com/subject/awfqsrtx.html