-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathRemove_K_Digits.cpp
37 lines (37 loc) · 927 Bytes
/
Remove_K_Digits.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
class Solution {
public:
string removeKdigits(string num, int k) {
if(k <= 0) return num;
int n = num.length();
stack<int> indx;
indx.push(0);
int i = 1;
while(i < n and k > 0) {
if(indx.empty()) {
indx.push(i);
i++;
}
while(i < n and num[i] >= num[indx.top()]) {
indx.push(i);
i++;
}
num[indx.top()] = '#';
indx.pop();
k--;
}
while(k > 0) {
num[indx.top()] = '#';
indx.pop();
k--;
}
string result;
for(i = 0; i < n and !(num[i] > '0' and num[i] <= '9'); ++i);
for(; i < n; ++i) {
if(num[i] != '#') {
result += num[i];
}
}
if(result.empty()) result = "0";
return result;
}
};