Skip to main content

Solution 5: Balanced Brackets

Given a string that contains only the characters ( ) [ and ], determine whether the input string contains no unmatched brackets. Brackets are said to match if every opening bracket has its closing complement subsequent in the string. The string is said to have balanced brackets if all brackets are matched and any subset of brackets enclosed within a matched pair of brackets is also a matched pair of brackets.

Return true if the bracket string is balanced, and false otherwise.

def balanced_brackets(string)
stack = []
opening = {
'{' => '}',
'[' => ']',
'(' => ')'
}
balanced = true
for bracket in string.split('')
if opening.keys.include? bracket
stack.push bracket
else
if opening[stack.last] == bracket
stack.pop
else
balanced = false
break
end
end
end
balanced
end