My simple c++ solution without using stack


  • 0
    Z
    class Solution {
    public:
        string removeKdigits(string num, int k) {
            if (num.length() == k) {
                return "0";
            }
            
            auto it = num.begin();
            
            while (k) {
                if (it + 1 == num.end() || *it > *(it + 1)) {
                    num.erase(it);
                    --it;
                    --k;
                } else {
                    ++it;
                }
            }
            
            while (num.length() > 1 && num[0] == '0') {
                num.erase(num.begin());
            }
            
            return num;
        }
    };
    

Log in to reply
 

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