Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> 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


It’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




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: