My Easy Understandable C++ Solution


  • 8
    G

    k is the number of char needs dropping, 'keep' is the number of char that should keep.
    We need to remove the beginning zeroes, and finally check if the result is empty of not.

    class Solution {
    public:
        string removeKdigits(string num, int k) {
            string res = "";
            int n = num.size(), keep = n - k;
            for (char c : num) {
                while (k && res.size() && res.back() > c) {
                    res.pop_back();
                    --k;
                }
                res.push_back(c);
            }
            res.resize(keep);
            while (!res.empty() && res[0] == '0') res.erase(res.begin());
            return res.empty() ? "0" : res;
        }
    };
    

  • 0
    J

    Thank your for your sharing.


Log in to reply
 

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