Leetcode 402 Solution

This article provides solution to leetcode question 402 (remove-k-digits)

https://leetcode.com/problems/remove-k-digits

Solution

class Solution {
public:
    string removeKdigits(string num, int k) {
        string res = "";

        for (char ch : num)
        {
            while (k && res.size() && ch < res[res.size() - 1])
            {
                res.pop_back();
                k--;
            }

            res.push_back(ch);
        }

        if (k >= res.size())
            return "0";
        else
            res = res.substr(0, res.size() - k);

        for (int i = 0; i < res.size(); i++)
            if (res[i] != '0')
                return res.substr(i);

        return "0";
    }
};