File tree Expand file tree Collapse file tree 1 file changed +20
-27
lines changed Expand file tree Collapse file tree 1 file changed +20
-27
lines changed Original file line number Diff line number Diff line change 11class Solution {
2- public String removeKdigits (String num , int k ) {
3-
4- if (k ==num .length () || k >num .length ()){
2+ public String removeKdigits (String num , int k ) {
3+ if (k >= num .length ())
54 return "0" ;
6- }
75
8- Stack <Character > st =new Stack <>();
9-
10- for (int i =0 ;i <num .length ();i ++){
11- char ch =num .charAt (i );
12- while (!st .isEmpty () && k >0 && st .peek ()>ch ){
13- st .pop ();
6+ Stack <Character > stack = new Stack <>();
7+ for (char d : num .toCharArray ()){
8+ while (!stack .empty () && d < stack .peek () && k > 0 ){
9+ stack .pop ();
1410 k --;
1511 }
16- st .push (ch );
12+ stack .push (d );
1713 }
18-
19- while (!st .isEmpty () && k >0 ){
20- st .pop ();
14+ while (!stack .empty () && k > 0 ){
15+ stack .pop ();
2116 k --;
2217 }
23-
24- StringBuilder sb = new StringBuilder ();
25- while (!st .isEmpty ())
26- sb .append (st .pop ());
27-
28- sb .reverse ();
2918
30- while (sb .length ()>1 && sb .charAt (0 )=='0' )
31- sb .deleteCharAt (0 );
32-
33- return sb .toString ();
34-
35-
19+ StringBuilder res = new StringBuilder ();
20+ while (!stack .empty ()){
21+ res .insert (0 , stack .pop ());
22+ }
3623
24+ for (int i = 0 ; i < res .length (); i ++){
25+ if (res .charAt (i ) != '0' ){
26+ return res .toString ().substring (i , res .length ());
27+ }
28+ }
29+ return "0" ;
3730 }
38- }
31+ }
You can’t perform that action at this time.
0 commit comments