forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path402.cpp
More file actions
48 lines (47 loc) · 1.13 KB
/
402.cpp
File metadata and controls
48 lines (47 loc) · 1.13 KB
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
class Solution {
public:
string removeKdigits(string num, int k) {
stack<int> s;
int i=0;
for( ;i<num.length(); i++) {
char c= num[i];
while(k && !s.empty() && s.top() > c){
s.pop();
k--;
}
if (k==0) {
break;
} else if (s.empty() || s.top() <= c) {
s.push(c);
}
}
if (k==0) {
for( ;i<num.length(); i++) {
s.push(num[i]);
}
} else {
while(k--) {
s.pop();
}
}
string str(s.size(), ' ');
for(int j=str.size()-1; j>=0; j--){
str[j] = s.top(); s.pop();
}
int lz = findLastZeroIdx(str);
switch (lz) {
case -2:
return "0";
default:
return str.substr(lz+1);
}
}
int findLastZeroIdx(string str) {
for(int i=0;i<str.length(); i++) {
if (str[i] != '0') {
return i-1;
}
}
return -2;
}
};