检查表达式中的每个括号是否都有匹配的右括号

时间:2017-04-22 05:37:12

标签: python regex python-3.x

我遇到一个问题,我必须评估数学表达式中使用的每个括号是否都有匹配的右括号。

例如:

  • 有效表达式:[(a+b)+b]
  • 无效表达:[(a+b}+b]

以下是我的代码:

str1 = input()
matches = {'(':')','[':']','{':'}'}
open = ['(','[','{']
close = [')',']','}']
track = []
negative = 0
for c in str1:
    if c in open:
        track.append(c)
    elif c in close:
        if c != matches[track[-1]]:
            negative = 1
            break
        else:
            del track[-1]
if negative == 1: 
    print ("False")
else:
    print ("True")

是否有更好的方法可以使用正则表达式?我的代码是否足够好还是可以优化?

2 个答案:

答案 0 :(得分:2)

根据您对表达式的处理方式,您可以轻松编写LL ParserShunting-Yard algorithm的代码。它们是解决此类问题的两种最常见的解决方案("解析"问题)。

答案 1 :(得分:0)

堆栈可以工作:

def validate(_str):
    braces = set("[](){}")
    opening = set("[({")
    closing = {"]":"[", ")":"(", "}":"{"}
    stack = list()

    for _char in _str:
        if _char in opening:
            stack.append(_char)
        elif _char in closing:
            if closing[_char] == stack[-1]:
                stack.pop()
            else:
                return False
    return True

print("Should be False:",validate("(a+b}+b"))
print("Should be True:",validate("(a+b)+b"))
print("Should be True:",validate("(a+[b-c+{d+e}])+b"))
print("Should be False:",validate("(a+]b-c+{d+e}])+b"))
相关问题