1255. Remove K Digits

Code(Language:C++) (Judger:ip-172-31-21-252)
class Solution {
public:
    /**
     * @param num: a string
     * @param k: an integer
     * @return: return a string
     */
    string removeKdigits(string &num, int k) {
        // write your code here
        //单调栈
        stack<char> stk; 
        string res; 
        for(int i = 0; i < num.size(); i++){
            while(!stk.empty() && stk.top() > num[i] && k > 0){
                stk.pop();
                k--; 
            }
            stk.push(num[i]); 
        }
        while(!stk.empty()){
            res = stk.top() + res; 
            stk.pop(); 
        }
        res = res.substr(0, num.size() - k); //corner case 重复的情况
        int idx = 0;
        while(res[idx] == '0' && idx < res.size()){ //corner case 0打头
            idx++; 
        }
        res = res.substr(idx); 
        return res.size() ? res : "0"; 
    }
};

Comments

Popular posts from this blog

算法的比较