Intern — Senior
Bracket nesting correctness check
livecode
Task condition
It is necessary to write a function areBracketsBalanced that determines whether brackets are correctly distributed in the given string expr. The string only allows characters of round, square, and curly brackets – ()[]{}. The function should return True when each opening bracket has a corresponding closing bracket in the correct order, and False otherwise.
def areBracketsBalanced(expr):
stack = []
for char in expr:
if char in ["(", "{", "["]:
stack.append(char)
else:
if not stack:
return False
current_char = stack.pop()
if current_char == "(":
if char != ")":
return False
if current_char == "{":
if char != "}":
return False
if current_char == "[":
if char != "]":
return False
return not stack