C++ O(n) 9 lines Single loop implementation.


  • 0
    J
        string removeKdigits(string num, int k) {
            string res;
            int i = 0, n = num.size(), deleteCount = k;
            if( k == num.size() ) return "0";
            while( i < num.size() ){
                if( res.size() && res[0] == '0' && n--) res.pop_back();
                else if( res.empty() || num[i] >= res.back() || deleteCount <= 0 ) res.push_back(num[i++]);
                else if (deleteCount-- > 0) res.pop_back();
            }
            return res.substr(0,n-k);    
        }
    

Log in to reply
 

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