Clean c++ solution without extra space


  • 0

    Update directly on original string as stack

    string removeKdigits(string num, int k) {
        int size = num.size();
        int top = 0, index = 0;
        while (k > 0 && index < size) {
            while (k > 0 && top > 0 && num[top - 1] > num[index]) {
                top--;
                k--;
            }
            num[top++] = num[index++];
        }
        while (index < size) {
            num[top++] = num[index++];
        }
        top -= k;
        index = 0;
        while (index < top && num[index] == '0')
            index++;
        return index >= top ? "0" : num.substr(index, top - index);
    }
    

Log in to reply
 

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