Untitled

mail@pastecode.io avatar
unknown
plain_text
10 months ago
718 B
3
Indexable
Never
class Solution {
public:
    string removeKdigits(string arr, int k) {
        stack<int>q;
        vector<int> num;
        for(auto i:arr) num.push_back(i-'0');

        for(int i:num){
            while(!q.empty() && i<q.top() && k>0){
                q.pop();
                k--;
            }
            q.push(i);
        }
        while(k-- && !q.empty()) q.pop(); //if there are still digits to be removed

        string ans="";
        while(!q.empty()) {
            ans = to_string(q.top()) + ans;;
            q.pop();
        }
        while(ans.length()>1 && ans[0]=='0'){
            ans=ans.substr(1);
        }
        if(ans=="") return "0";
        return ans;
    }
};
Leave a Comment