class Stack: def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def push(self,item): #添加元素进站 self.items.append(item) def peek(self): #打印栈顶元素 return self.items[len(self.items)-1] def pop(self): #从栈顶取出元素 return self.items.pop() def size(self): #返回栈中元素的个数 return len(self.items)
栈的另一种实现是把列表的首端(index=0)作为栈顶一样可以实现Stack
class Stack: def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def push(self,item): #添加元素进站 self.items.insert(0,item) def peek(self): #打印栈顶元素 return self.items[0] def pop(self): #从栈顶取出元素 return self.items.pop(0) def size(self): #返回栈中元素的个数 return len(self.items)
def parChecker(symbolString): #单一括号匹配函数 s=Stack() balanced=True index=0 #判断索引值和字符串的大小 ,当前是否匹配 while index<len(symbolString) and balanced: symbol=symbolString[index] if symbol =="(": s.push(symbol) else: if s.isEmpty(): balanced=False else: s.pop() index=index+1 if balanced and s.isEmpty(): return True else: return False
print(parChecker("(()))"))
def TYparChecker(symbolString): #多种类型括号匹配方法 s=Stack() balanced=True index=0 while index<len(symbolString) and balanced: symbol=symbolString[index] if symbol in '([{': s.push(symbol) else: if s.isEmpty(): balanced= False else: top=s.pop() if not matchs(top,symbol): balanced=False index=index+1 if balanced and s.isEmpty(): return True else: return False def matchs(open,close): opens='([{' closers=')]}' return opens.index(open)==closers.index(close)
print(TYparChecker("{{[()]}"))