Skip to content

Commit be6fd15

Browse files
Create remove_k_digits.cpp
1 parent a166a70 commit be6fd15

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

remove_k_digits.cpp

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public:
3+
string removeKdigits(string num, int k) {
4+
if(num.size() == 0) return "";
5+
6+
int i = 0;
7+
while(k > 0) { //k--
8+
9+
//triggered when i > 0
10+
i = (i > 0) ? i - 1 : 0; //bring the i back to peak before the previously removed peak
11+
12+
while(i<num.size() - 1 && num[i] <= num[i+1]) {
13+
i++;
14+
} // get the peak
15+
16+
num.erase(num.begin() + i); //remove the peak
17+
k--; //decrement k
18+
}
19+
20+
21+
auto nonzero_int = num.find_first_not_of("0");
22+
num.erase(0, nonzero_int); //remove head 0's
23+
24+
if(num.size() == 0) return "0";
25+
return num;
26+
}
27+
};

0 commit comments

Comments
 (0)