括号匹配问题 python解法(栈)

  括号匹配问题可以说是栈的经典运用了 我们可以遍历输入的字符串如果遇到前半个括号如“(,{,[ ” 就将它们压入栈,遇到后半个括号就弹出栈顶元素查看是否匹配。

但是python并没有栈,这里提供两种办法一种是利用列表来模拟栈,另一种是用queue模块中的 LifoQueue 来当栈使用。

接下来上代码:

from queue import LifoQueue

str = input()

def panduan(str):
    sta = LifoQueue()
    s1 = {'[', '(', '{'}
    s2 = {']', '}', ')'}
    dic = {'[': ']', '{': '}', '(': ')'}

    for c in str:
        if c in s1:
            sta.put(c)
        elif c in s2:
            try:
                if dic[sta.get()] == c:
                    continue
                else:
                    return False
            except:
                return False
    return True



def panduan1(str):
    sta = list()
    s1 = {'[', '(', '{'}
    s2 = {']', '}', ')'}
    dic = {'[': ']', '{': '}', '(': ')'}

    for c in str:
        if c in s1:
            sta.append(c)
        elif c in s2:
            try:
                if dic[sta.pop()] == c:
                    continue
                else:
                    return False
            except:
                return False
    return True

print("YES" if panduan(str) else "NO")   
print("YES" if panduan1(str) else "NO")

 

 

 

posted @ 2023-03-27 15:46  CH-Yu  阅读(27)  评论(0)    收藏  举报  来源