File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ string removeKdigits (string num, int k) {
4
+ stack<int > s;
5
+ int i=0 ;
6
+ for ( ;i<num.length (); i++) {
7
+ char c= num[i];
8
+ while (k && !s.empty () && s.top () > c){
9
+ s.pop ();
10
+ k--;
11
+ }
12
+ if (k==0 ) {
13
+ break ;
14
+ } else if (s.empty () || s.top () <= c) {
15
+ s.push (c);
16
+ }
17
+ }
18
+ if (k==0 ) {
19
+ for ( ;i<num.length (); i++) {
20
+ s.push (num[i]);
21
+ }
22
+ } else {
23
+ while (k--) {
24
+ s.pop ();
25
+ }
26
+ }
27
+ string str (s.size (), ' ' );
28
+ for (int j=str.size ()-1 ; j>=0 ; j--){
29
+ str[j] = s.top (); s.pop ();
30
+ }
31
+
32
+ int lz = findLastZeroIdx (str);
33
+ switch (lz) {
34
+ case -2 :
35
+ return " 0" ;
36
+ default :
37
+ return str.substr (lz+1 );
38
+ }
39
+ }
40
+ int findLastZeroIdx (string str) {
41
+ for (int i=0 ;i<str.length (); i++) {
42
+ if (str[i] != ' 0' ) {
43
+ return i-1 ;
44
+ }
45
+ }
46
+ return -2 ;
47
+ }
48
+ };
You can’t perform that action at this time.
0 commit comments