-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveKDigits.cpp
More file actions
42 lines (36 loc) · 794 Bytes
/
RemoveKDigits.cpp
File metadata and controls
42 lines (36 loc) · 794 Bytes
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
class Solution {
public:
string removeKdigits(string num, int k) {
if (num.size() == k)
return "0";
int i = 0;
stack<char> stk;
while (i < num.size())
{
while (k && !stk.empty() && stk.top() > num[i])
{
stk.pop();
k--;
}
stk.push(num[i++]);
}
while (k--)
{
stk.pop();
}
string res(stk.size(), '0');
i = stk.size();
while (i)
{
res[i-1] = stk.top();
stk.pop();
i--;
}
i = 0;
while (i < res.size() && res[i] == '0')
{
res.erase(i, 1);
}
return res.size() == 0 ? "0" : res;
}
};