写一个栈的类:stack.py
class Stack:
def __init__(self):
self.items = []
def is_Empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(items)-1]
def size(self):
return len(self.items)
实现括号匹配的算法程序:
from stack import Stack
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol == "(":
s.push(symbol)
elif symbol == ")":
if s.is_Empty():
balanced = False
else:
s.pop()
index += 1
if balanced and s.is_Empty():
return True
else:
return False
print(parChecker("(((2356)))"))
输出结果:
True
再测试
print(parChecker("(()))"))
输出结果False
能够匹配多种括号,{},[]
只需要小小的改动代码:
from stack import Stack
def parChecker(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in "({[":
s.push(symbol)
elif symbol in ")}]":
if s.is_Empty():
balanced = False
else:
s.pop()
index += 1
if balanced and s.is_Empty():
return True
else:
return False
print(parChecker("[(({fdf}))]"))
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。