您好,登錄后才能下訂單哦!
寫一個棧的類: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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。