File tree Expand file tree Collapse file tree 3 files changed +30
-24
lines changed
solution/0400-0499/0402.Remove K Digits Expand file tree Collapse file tree 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 {
145145
146146``` ts
147147function 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 -- ;
153153 }
154- nums .splice (idx , 1 );
155- k -- ;
154+ stk .push (c );
156155 }
157- return nums .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
156+ while (k -- ) {
157+ stk .pop ();
158+ }
159+ return stk .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
158160}
159161```
160162
Original file line number Diff line number Diff line change @@ -131,16 +131,18 @@ func removeKdigits(num string, k int) string {
131131
132132``` ts
133133function 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 -- ;
139139 }
140- nums .splice (idx , 1 );
141- k -- ;
140+ stk .push (c );
142141 }
143- return nums .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
142+ while (k -- ) {
143+ stk .pop ();
144+ }
145+ return stk .join (' ' ).replace (/ ^ 0* / g , ' ' ) || ' 0' ;
144146}
145147```
146148
Original file line number Diff line number Diff line change 11function 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 -- ;
77 }
8- nums . splice ( idx , 1 ) ;
9- k -- ;
8+ stk . push ( c ) ;
109 }
11- return nums . join ( '' ) . replace ( / ^ 0 * / g, '' ) || '0' ;
10+ while ( k -- ) {
11+ stk . pop ( ) ;
12+ }
13+ return stk . join ( '' ) . replace ( / ^ 0 * / g, '' ) || '0' ;
1214}
You can’t perform that action at this time.
0 commit comments