Ruby solution using stack


  • 0
    B
    def remove_kdigits(num, k)
        res = []
        num.chars.each do |d|
            while k!= 0 && !res.empty? && res[-1] > d
                res.pop
                k -= 1
            end
            res << d
        end
        
        while !res.empty? && k > 0
            res.pop
            k -= 1
        end
        return '0' if res.empty?
        return res.join().to_i.to_s
    end
    

Log in to reply
 

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