5 ms·
> map ... two arrays 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 manipu
by pdkl95 8y ago
> map ... two arrays
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
- braythwayt 8y agoIt’s my favourite (“favourite” is not synonymous with “best” by any metric other than amusement) solution as well: http://raganwald.com/2018/11/14/dyck-joke.html http://raganwald.com/2018/11/14/dyck-joke.html