Posted on

Description

Submission

class Solution {
public:
    string removeKdigits(string num, int k) {
        stack<char> Stack;

        int i = 0;
        for(; k != 0 && i < num.length(); ++i) {
            char c = num[i];
            for(; !Stack.empty() && c < Stack.top() && k > 0; k--) {
                Stack.pop();
            }
            Stack.push(c);
        } 

        string ret = "";

        // cout << Stack.size() << endl;

        while(!Stack.empty()) {
            // cout << Stack.top() << endl;
            ret = string(1, Stack.top()) + ret;
            Stack.pop();
        }
        // cout << k << endl;
        // cout << ret;

        if(k == 0) {
            ret += num.substr(i, num.length() - i);
        } else {
            ret = ret.substr(0, ret.size() - k);
        }

        
        while(!ret.empty() && ret[0] == '0') {
            ret = ret.substr(1, ret.size() - 1);
        }

        if(ret.empty()) return "0";

        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *