File tree 3 files changed +30
-24
lines changed
solution/0400-0499/0402.Remove K Digits
3 files changed +30
-24
lines changed Original file line number Diff line number Diff line change @@ -145,16 +145,18 @@ func removeKdigits(num string, k int) string {
145
145
146
146
``` ts
147
147
function removeKdigits(num : string , k : number ): string {
148
- let nums = [... num ];
149
- while ( k > 0 ) {
150
- let idx = 0 ;
151
- while ( idx < nums . length - 1 && nums [ idx + 1 ] >= nums [ idx ]) {
152
- idx ++ ;
148
+ const stk : string [] = [];
149
+ for ( const c of num ) {
150
+ while ( k && stk . length > 0 && stk [ stk . length - 1 ] > c ) {
151
+ stk . pop ();
152
+ k -- ;
153
153
}
154
- nums .splice (idx , 1 );
155
- k -- ;
154
+ stk .push (c );
156
155
}
157
- return nums .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
156
+ while (k -- ) {
157
+ stk .pop ();
158
+ }
159
+ return stk .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
158
160
}
159
161
```
160
162
Original file line number Diff line number Diff line change @@ -131,16 +131,18 @@ func removeKdigits(num string, k int) string {
131
131
132
132
``` ts
133
133
function removeKdigits(num : string , k : number ): string {
134
- let nums = [... num ];
135
- while ( k > 0 ) {
136
- let idx = 0 ;
137
- while ( idx < nums . length - 1 && nums [ idx + 1 ] >= nums [ idx ]) {
138
- idx ++ ;
134
+ const stk : string [] = [];
135
+ for ( const c of num ) {
136
+ while ( k && stk . length > 0 && stk [ stk . length - 1 ] > c ) {
137
+ stk . pop ();
138
+ k -- ;
139
139
}
140
- nums .splice (idx , 1 );
141
- k -- ;
140
+ stk .push (c );
142
141
}
143
- return nums .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
142
+ while (k -- ) {
143
+ stk .pop ();
144
+ }
145
+ return stk .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
144
146
}
145
147
```
146
148
Original file line number Diff line number Diff line change 1
1
function removeKdigits ( num : string , k : number ) : string {
2
- let nums = [ ... num ] ;
3
- while ( k > 0 ) {
4
- let idx = 0 ;
5
- while ( idx < nums . length - 1 && nums [ idx + 1 ] >= nums [ idx ] ) {
6
- idx ++ ;
2
+ const stk : string [ ] = [ ] ;
3
+ for ( const c of num ) {
4
+ while ( k && stk . length > 0 && stk [ stk . length - 1 ] > c ) {
5
+ stk . pop ( ) ;
6
+ k -- ;
7
7
}
8
- nums . splice ( idx , 1 ) ;
9
- k -- ;
8
+ stk . push ( c ) ;
10
9
}
11
- return nums . join ( '' ) . replace ( / ^ 0 * / g, '' ) || '0' ;
10
+ while ( k -- ) {
11
+ stk . pop ( ) ;
12
+ }
13
+ return stk . join ( '' ) . replace ( / ^ 0 * / g, '' ) || '0' ;
12
14
}
You can’t perform that action at this time.
0 commit comments