Naive straight-forward 9-line c++ solution with explanation


  • 0

    Every time scan from the beginning and erase the last digit of the heading non-descending sequence.
    e.g. 44322344 => 4322344 => 322344 => 22344 => 2234 => 223 => 22 => 2 => 0

    string removeKdigits(string num, int k) {
        for (int i = 0; i < k; i++) {
            int p;
            for (p = 0; p + 1 < num.size() && num[p] <= num[p + 1]; p++);
            num.erase(num.begin() + p);
        }
        int p;
        for (p = 0; p < num.size() && num[p] == '0'; p++);
        num.erase(num.begin(), num.begin() + p);
        return num.empty() ? "0" : num;
    }
    

Log in to reply
 

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