Ruby solution with stack


  • 0
    C
    def process(stack, token)
      case token
        when '+', '-', '('
          stack.push(token)
        when ')'
          prev_token = stack.pop
          b = stack.pop # pop opening bracket
          raise "Unbalanced brackets" unless b == '('
          process(stack, prev_token) # replace  at the top of the stack (v) with just v and execute previous expression
        when Fixnum
          if ['+', '-'].include?(stack.last)
            op = stack.pop
            v1 = stack.pop
            v2 = token.to_i
    
            res = v1.send(op, v2)
            stack.push(res)
          else
            stack.push(token.to_i)
          end
        else
          raise "Unexpected token #{token.inspect}"
      end
    end
    
    
    def tokenize(s)
      chars = s.gsub(/\s+/, '').split('')
    
      chars.inject([]) do |accum, char|
        if char =~ /\d/
          accum.last.is_a?(Fixnum) ? accum.push(accum.pop * 10 + char.to_i) : accum.push(char.to_i)
        else
          accum.push(char)
        end
    
        accum
      end
    end
    
    # @param {String} s
    # @return {Integer}
    def calculate(s)
      stack = []
    
      tokens = tokenize(s)
      tokens.each do |c|
        process(stack, c)
      end
    
      stack.first
    end

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.