您好,登錄后才能下訂單哦!
寫一個(gè)棧的類: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)
實(shí)現(xiàn)括號匹配的算法程序:
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)))"))
輸出結(jié)果:
True
再測試
print(parChecker("(()))"))
輸出結(jié)果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}))]"))
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。