删除 k 个元素,使剩下的数字最小(单调栈)

给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。

注意:

num 的长度小于 10002 且 ≥ k。
num 不会包含任何前导零。
示例 1 :

输入: num = "1432219", k = 3
输出: "1219"
解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。
示例 2 :

输入: num = "10200", k = 1
输出: "200"
解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。
示例 3 :

输入: num = "10", k = 2
输出: "0"
解释: 从原数字移除所有的数字,剩余为空就是0。

思路:单调栈即可,当删除的元素个数 = k 时直接退出循环,若退出循环的时候个数 < k,则从末尾在删掉一些元素,直至它的个数 = k

代码:

class Solution {
public:
    string removeKdigits(string num, int k) {
        stack<char>sta;
        while(!sta.empty()) sta.pop();

        int cnt = 0;
        for(int i = 0; i < num.size(); i++){
            if (sta.empty()) sta.push(num[i]);
            else {
                while(!sta.empty() && sta.top() > num[i] && cnt < k){
                    sta.pop(); cnt++;
                }
                sta.push(num[i]);
            }
        };
        while(cnt < k) {
            sta.pop(); cnt++;
        }
        stack<char>mid;
        while(!sta.empty()) {
            char ch = sta.top(); sta.pop();
            mid.push(ch);
        }
        string ans = "";
        while(!mid.empty()) {
            char ch = mid.top();
            if (ch != '0') break;
            else mid.pop();
        }
        while(!mid.empty()){
            char ch = mid.top(); mid.pop();
            ans += ch;
        }
        if (ans.size() == 0) ans += '0';
        return ans;
    }
};

  

原文地址:https://www.cnblogs.com/ccut-ry/p/13975982.html