棧的一個經典應用就是判斷一個文本中的括號,包括小括號,中括號,大括號是不是有缺失,順序不正確等情況。
棧的類的實現在前面文章中已經實現,我們這裏直接應用(用的是順序表實現的棧)
兩種解法:第二種解法有細節
第一種解答法如下:
# _*_ coding:utf-8 _*_
"""
用於檢查文本中的括號是不是使用正確,
對於文本中括號的缺少等問題都能夠檢測
"""
from 棧的順序表實現 import Stack, StackOverFlow
parensK = "([{"
parensG = ")]}"
parensDict = { ")" : "(", "]" : "[", "}" : "{" }
# 建立一個棧的實例
class Solution:
stack = Stack()
def __init__(self, string):
self.string = string
def check(self):
for char in self.string:
'''
遍歷字符串,找出括號字符進行判斷
'''
if char in parensK:
self.stack.push(char)
elif char in parensG:
pchar = self.stack.pop()
if parensDict[char] != pchar:
raise StackOverFlow("A not match char")
if not self.stack.is_empty():
raise StackOverFlow("dont shut it down")
string = "({}[()])"
solution = Solution(string)
solution.check()
第二種解法代碼如下:
# _*_ coding:utf-8 _*_
"""
一下這個實現方法,利用了棧的存儲原理
但是破壞了棧的操作,可以輸出整個文本中
所有括號的出現順序
"""
from 棧的順序表實現 import Stack, StackOverFlow
def check_parens(text):
"""
括號配對檢查函數,text是被檢查的文本
"""
parens = "()[]{}"
open_parens = "([{"
opposite = { ")" : "(", "]" : "[", "}" : "{" }
# 用字典來檢測
def parentheses(text):
"""
括號生成器,每次調用返回下一次text裏的下一個括號及其位置
使用一個生成器來每次調度都會生成text中的下一個括號
"""
i, text_len = 0, len(text)
while True:
while i < text_len and text[i] not in parens:
i += 1
if i >= text_len:
return
yield text[i], i
i += 1
st = Stack()
# 保存括號的棧
for pr, i in parentheses(text):
"""
這裏就調用了生成器函數
"""
if pr in open_parens:
st.push(pr)
elif st.pop() != opposite[pr]:
# 這裏首先執行st.pop(),所以棧頂的元素一定會被刪除
print("Unmatching is found at", i , "for", pr)
return False
print("All parentheses are correctly matched")
return True
check_parens("([]{}())")