leetcode - 402. 移掉 K 位数字
题目
代码
#include
#include
#include
using namespace std;
string removeKdigits(string num, int k) {
int n = num.size();
if(n == 0 || k == n){
return "0";
}
vector stk;
for(int i = 0; i < n; i++){
while(stk.size() > 0 && stk.back() > num[i] && k){
stk.pop_back();
k--;
}
stk.push_back(num[i]);
}
while(k > 0){
stk.pop_back();
k--;
}
string res = "";
int flag = 1; // 标记是否存在前导0
for(int i = 0; i < stk.size(); i++){
if(flag && stk[i] == '0'){
continue;
}
flag = 0;
res += stk[i];
}
return res == "" ? "0" : res;
}
int main(){
string num, res;
int k;
cin>>num>>k;
res = removeKdigits(num, k);
cout<