Skip to content

Commit 25910bc

Browse files
authored
Create 402. Remove K Digits
1 parent ceca8a9 commit 25910bc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

402. Remove K Digits

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
string removeKdigits(string num, int k) {
4+
if (num.length() == k)
5+
return "0";
6+
7+
string ans;
8+
vector<char> stack;
9+
10+
for (int i = 0; i < num.length(); ++i) {
11+
while (k > 0 && !stack.empty() && stack.back() > num[i]) {
12+
stack.pop_back();
13+
--k;
14+
}
15+
stack.push_back(num[i]);
16+
}
17+
18+
while (k-- > 0)
19+
stack.pop_back();
20+
21+
for (const char c : stack) {
22+
if (c == '0' && ans.empty())
23+
continue;
24+
ans += c;
25+
}
26+
27+
return ans.empty() ? "0" : ans;
28+
}
29+
};

0 commit comments

Comments
 (0)