If we're allowed to use more memory than a simple stack, this is my favorite super-cheaty solution. It abuses ruby's builtin string manipulation to recursively delete inner matched pairs (all that is really needed is a "slide remaining string left 2 chars" function). Since this only needs to match two-char long inner pairs, it trivially extends to multiple matched bracket types.
BRACKET_RE = /\(\)/
#BRACKET_RE = /\(\)|\[\]|\{\}/
def balanced?(str)
case str
when '' then return true
when BRACKET_RE then balanced? str.split(BRACKET_RE).join('')
else return false
end
end
If we're allowed to use more memory than a simple stack, this is my favorite super-cheaty solution. It abuses ruby's builtin string manipulation to recursively delete inner matched pairs (all that is really needed is a "slide remaining string left 2 chars" function). Since this only needs to match two-char long inner pairs, it trivially extends to multiple matched bracket types.