1
// ��������Please upvote if it helps ��������
2
class Solution {
3
public:
4
string removeKdigits(string num, int k) {
5
// number of operation greater than length we return an empty string
6
if (num.length() <= k) return "0";
7

8
// k is 0 , no need of removing / preforming any operation
9
if (k == 0) return num;
10

11
string res = ""; // result string
12
stack<char> s; // char stack
13

14
s.push(num[0]); // pushing first character into stack
15

16
for (int i = 1; i < num.length(); ++i) {
17
while (k > 0 && !s.empty() && num[i] < s.top()) {
18
// if k greater than 0 and our stack is not empty and the upcoming
19
// digit, is less than the current top than we will pop the stack top
20
--k;
21
s.pop();
22
}
23

24
s.push(num[i]);
25

26
// popping preceding zeroes
27
if (s.size() == 1 && num[i] == '0') s.pop();
28
}
29

30
while (k && !s.empty()) {
31
// for cases like "456" where every num[i] > num.top()
32
--k;
33
s.pop();
34
}
35

36
while (!s.empty()) {
37
res.push_back(s.top()); // pushing stack top to string
38
s.pop(); // pop the top element
39
}
40

41
reverse(res.begin(), res.end()); // reverse the string
42

43
if (res.length() == 0) return "0";
44

45
return res;
46
}
47
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0