very concise C++ solution


  • 0
    H
    class Solution {
    public:
        string removeKdigits(string num, int k) {
            string ans;
            int n = k, len = num.size(), cnt = 0;
            for(auto val: num)
            {
                while(!ans.empty() &&  val < ans.back() && n-- > 0)
                    ans.pop_back();
                ans.push_back(val);
            }
            while(ans[cnt]=='0') cnt++;
            ans = ans.substr(cnt, len-k-cnt);
            return !ans.size()?"0":ans;
        }
    };
    

Log in to reply
 

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