forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0402-remove-k-digits.cpp
37 lines (31 loc) · 880 Bytes
/
0402-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
// Time Complexity is O(N) where N is the size of the input string.
// Space complexity is O(N) as well
classSolution {
public:
string removeKdigits(string num, int k) {
int n = num.size();
stack<char>s;
int count = k;
for(int i = 0 ; i < n; i++)
{
while(!s.empty() && count > 0 && s.top() > num[i])
{
s.pop();
count--;
}
s.push(num[i]);
}
// In case the num was already in a non increasing order (e.x: 123456)
while(s.size() != n - k) s.pop();
string res = "";
while(!s.empty())
{
res += s.top();
s.pop();
}
reverse(res.begin() , res.end());
// Remove the zeros from the left if they exist.
while (res[0] == '0') res.erase(0 , 1);
return (res == "") ? "0": res;
}
};