3ms c++ and a way to promote


  • 0
    E

    Remove the first decreased digit, if all digits are increased, pop back it.

    string removeKdigits(string num, int k) {
        if(k>=num.size())return "0";
        string res(1,num[0]);
        int i=1;
        while(k>0){
            if(i==num.size()||res.back()>num[i]){res.pop_back();k--;}
            else{
                if(res!=""||num[i]!='0')res+=num[i];
                i++;
            }
        }
        for(;i<num.size();i++)if(res!=""||num[i]!='0')res+=num[i];
        return res==""?"0":res;
    }
    

    For more, there is a way to promote this solution, if k<len(num)/2, remove k digits; Else, select len(num)/2-k digits. Such promotion can make Tn=O(n/2)


Log in to reply
 

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