1255. Remove K Digits
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
Post a Comment