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("(((())"))
网友评论