Stacks: Balanced Brackets

  • + 0 comments

    Clean Ruby solution:

    BRACKETS = {
      '(' => ')',
      '{' => '}',
      '[' => ']'
    }
    
    def is_balanced(expression)
      stack = []
      expression.each_char do |c|
        if BRACKETS.key? c
          stack << c
        elsif BRACKETS[stack.pop] != c
          return false
        end
      end
      stack.empty?
    end
    
    gets.to_i.times do
      puts is_balanced(gets.chomp) ? 'YES' : 'NO'
    end