【leetcode 字典序列删除 C++】402. Remove K Digits

402. Remove K Digits

在这里插入图片描述

class Solution {
    
    
public:
    string removeKdigits(string num, int k) {
    
    
        if(num.size() <= k) return "0";
        char S[num.size()];
        int top = -1;
        int remain = num.size() - k;
        for(auto ch : num) {
    
    
            while(k && top != -1 && ch < S[top]) {
    
    
                top--;
                k--;
            }
            S[++top] = ch;
        }
        string ans = "";
        for(int ii = 0; ii <= top; ii++) {
    
    
            if(S[ii] == '0' && ans.size() == 0) continue;
            ans += S[ii];
            if(ans.size() == remain) break;
        }
        return ans == "" ? "0" : ans;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/114363766