2017-04-22 64 views
1

我遇到了一個問題,即必須評估數學表達式中使用的每個大括號是否具有匹配的大括號。檢查表達式中的每個大括號是否有匹配的大括號

例如:

  • 有效的表達式:[(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") 

是否有這樣做的更好的辦法它如使用正則表達式?我的代碼足夠好還是可以優化?

+0

注意,該代碼引發錯誤等的輸入「)」,因爲賽道是在一開始是空的。 –

+0

[Regex用於檢查一個字符串是否有不匹配的括號?]的可能的重複(http://stackoverflow.com/questions/562606/regex-for-checking-if-a-string-has-mismatched-parentheses) – abccd

+0

有參考到[http://stackoverflow.com/questions/562606/regex-for-checking-if-a-string-has-mismatched-parentheses],正則表達式不適合該任務。你這樣做的方式是理想的。 – Windmill

回答

2

根據你想要對你的表情做什麼,你可以很容易地編碼LL ParserShunting-Yard algorithm。他們是這類問題的兩個最常見的解決方案(「解析」問題)。

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"))