Rosetta Code Popular
Balanced Brackets
Check whether bracket pairs are properly nested and closed by scanning the text with a stack.
Source
rosettacode/popular/balanced_brackets.vibe
# title: Balanced Brackets
# source: https://rosettacode.org/wiki/Balanced_brackets
# category: Rosetta Code Popular
# difficulty: Easy
# summary: Check whether bracket pairs are properly nested and closed by scanning the text with a stack.
# tags: popular, parsing, stack, strings
# vibe: 0.2
def opener_for(char)
if char == ")"
"("
elsif char == "]"
"["
elsif char == "}"
"{"
else
nil
end
end
def closer?(char)
char == ")" || char == "]" || char == "}"
end
def balanced_brackets?(text)
stack = []
depth = 0
index = 0
while index < text.length
char = text.slice(index)
if char == "(" || char == "[" || char == "{"
stack = stack.push(char)
depth = depth + 1
elsif closer?(char)
if depth == 0
return false
end
popped = stack.pop
stack = popped[:array]
depth = depth - 1
if popped[:popped] != opener_for(char)
return false
end
end
index = index + 1
end
depth == 0
end
def run
{
nested_true: balanced_brackets?("{[()()]}"),
mixed_true: balanced_brackets?("function(x) { return [x, x + 1] }"),
crossed_false: balanced_brackets?("([)]"),
incomplete_false: balanced_brackets?("{[()}")
}
end
Output
Press run to execute run from this example.