Share my concise C++ solution


  • 1

    Reverse thinking to remain len - k number, every time find the minimum available number

        string removeKdigits(string num, int k) {
            int len = num.size();
            if( len == k) return string("0");
            
            string res;
            k = len-k;
            int beg_idx = 0;
            while(k){
                int min_idx = beg_idx;
                for(int i=min_idx; i<=len-k; ++i){
                    if(num[min_idx] > num[i]){
                        min_idx = i;
                    }
                }
                if(!res.empty() || num[min_idx] != '0' || k==1 ){
                    res.push_back(num[min_idx]);    
                }
                beg_idx = min_idx + 1;
                k--;
            }
            return res;
        }
    

Log in to reply
 

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