-
Notifications
You must be signed in to change notification settings - Fork 3
/
402.cpp
36 lines (33 loc) · 886 Bytes
/
402.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
string removeKdigits(string num, int k) {
if (k >= num.size()) return "0";
stack<int> st;
for (auto& c : num) {
int digit = c - '0';
if (!st.empty() && digit >= st.top()) {
st.push(digit);
}
else {
while (!st.empty() && digit < st.top() && k) {
st.pop();
k--;
}
st.push(digit);
}
}
while (k) {
st.pop();
k--;
}
string res = "";
while (!st.empty()) {
res.push_back(st.top() + '0');
st.pop();
}
while (!res.empty() && res.back() == '0') res.pop_back();
if (res.size() == 0) return "0";
reverse(res.begin(), res.end());
return res;
}
};