-
Notifications
You must be signed in to change notification settings - Fork 12
/
solution.cpp
59 lines (57 loc) · 1.44 KB
/
solution.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.length();
stack<char> st;
for (int i = 0; i < n; ++i) {
if (st.empty()) {
st.push(num[i]);
} else if (st.top() > num[i] && k > 0) {
while (!st.empty() && st.top() > num[i] && k > 0) {
st.pop();
--k;
}
st.push(num[i]);
} else {
st.push(num[i]);
}
}
while (!st.empty() && k > 0) {
st.pop();
--k;
}
string res;
if (st.empty()) {
res = '0';
}
while (!st.empty()) {
res += st.top();
st.pop();
}
reverse(res.begin(), res.end());
// remove leading zeroes
string finalRes;
int firstIdx = 0;
int finalLen = res.length();
while (firstIdx < finalLen && res[firstIdx] == '0') {
++firstIdx;
}
if (firstIdx == finalLen) {
finalRes = '0';
} else {
while (firstIdx < finalLen) {
finalRes += res[firstIdx];
++firstIdx;
}
}
return finalRes;
}
};
int main() {
Solution solver;
cout << solver.removeKdigits("1234567890", 9) << endl;
}