当你看到一个关闭字符时,简单地尝试从堆栈中弹出一个关闭字符要容易得多,如果不可能则会失败.
pairs = dict(tuple(pair) for pair in ["()", "[]", "{}"]) # pairs["("] == ")" # pairs["["] == "]" # etc def parenthesesMatch(match): s = Stack() for char in match: # Not "] } )" if char in pairs.values() and pairs[s.pop()] != char: return False elif char in pairs: s.push(char) return s.isEmpty()