C++ 3ms simple solution with comments.


  • 0
    Z
    class Solution {
    public:
        string removeKdigits(string num, const int k) {
            if (num.size() <= k) {
                return "0";
            }
            if (num == "0") {
                return num;
            }
            string res; 
            // We always choose to pop out the largest value in the stack.
            int deleted = 0;
            for (int i = 0; i < num.size(); ++i) {
                if (res.empty() && num[i] == '0') {
                    // Lead value cannot be 0. So skip to the next value.
                    continue;
                }
                if (deleted == k || res.empty() || num[i] >= res.back()) {
                    // 3 conditions:
                    //   1, We have deleted enough value, so simply insert all remains.
                    //   2, No available value right now, in this case num[i] != '0' by default,
                    //      so insert it.
                    //   3, The next value is larger, so insert it as it should have a higher priority 
                    //      to delete the the current top one in stack.
                    res.push_back(num[i]);
                    continue;
                }
                // Pop all previous string out.
                // We meet a value smaller than the current stack top, so delete the current stack top.
                res.pop_back();
                --i;
                ++deleted;
            }
            // res: first element is not 0, but its length maybe longer or shorter as deleted may not equal to k.
            res = res.substr(0, num.size() - k);
            return res.empty() ? "0" : res;
        }
    };
    

Log in to reply
 

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