-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path402.cpp
More file actions
50 lines (41 loc) · 1.02 KB
/
Copy path402.cpp
File metadata and controls
50 lines (41 loc) · 1.02 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
49
50
#include <string>
using namespace std;
class Solution {
public:
string removeKdigits(string num, int k) {
string st;
for (char c : num) {
while (k > 0 && !st.empty() && st.back() > c) {
st.pop_back();
k--;
}
st.push_back(c);
}
while (k > 0 && !st.empty()) {
st.pop_back();
k--;
}
int i = 0;
while (i < st.size() && st[i] == '0')
i++;
string res = st.substr(i);
return res.empty() ? "0" : res;
}
private:
string twoPointersRemoveKdigits(string num, int k) {
int l = 0;
for (int r=0; r < num.size(); r++) {
while (l>0 && k>0 && num[l-1] > num[r]) {
l--;
k--;
}
num[l++] = num[r];
}
l -= k;
int i = 0;
while (i<l && num[i] == '0')
i++;
if (i == l) return "0";
return num.substr(i, l-i);
}
};