402. Remove K Digits -- javascript code


  • 0
    E
    /**
     * @param {string} num
     * @param {number} k
     * @return {string}
     */
    var removeKdigits = function(num, k) {
        var len = num.length;
        if(len==k){
            return "0";
        }
        var stack = [];
        var nums = num.split("");
        nums.forEach(function(item){
            item = parseInt(item);
        });
        var left = len - k;
        for(var i=0;i<left;i++){
            stack.push(nums[i]);
        }
        margin = 0;
        for(i=1;i<len;i++){
            cur = nums[i];
            range = len-i;
            if(range>=left){
                thestart = 0;
            }else{
                thestart = left-range;
            }
            var end = Math.min(i-margin,left);
            for(var j=thestart;j<end;j++){
                if(cur<stack[j]){
                    stack[j] = cur;
                    margin = i-j;
                    break;
                }
            }
            for(var n=j+1,m=1;n<left;n++,m++){
                stack[n] = nums[i+m];
            }
            //console.log(stack);
        }
        var ret = stack.join("").replace(/^0{1,}/,"");
        return ret===""?"0":ret;
    };
    

Log in to reply
 

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