File tree 1 file changed +20
-27
lines changed
1 file changed +20
-27
lines changed Original file line number Diff line number Diff line change 1
1
class 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 ())
5
4
return "0" ;
6
- }
7
5
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 ();
14
10
k --;
15
11
}
16
- st .push (ch );
12
+ stack .push (d );
17
13
}
18
-
19
- while (!st .isEmpty () && k >0 ){
20
- st .pop ();
14
+ while (!stack .empty () && k > 0 ){
15
+ stack .pop ();
21
16
k --;
22
17
}
23
-
24
- StringBuilder sb = new StringBuilder ();
25
- while (!st .isEmpty ())
26
- sb .append (st .pop ());
27
-
28
- sb .reverse ();
29
18
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
+ }
36
23
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" ;
37
30
}
38
- }
31
+ }
You can’t perform that action at this time.
0 commit comments