File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ package Monotonic_Stack ;
2
+
3
+ // Problem Statement: Remove K Digits (hard)
4
+ // LeetCode Question: 402. Remove K Digits
5
+
6
+ import java .util .Stack ;
7
+
8
+ public class Problem_6_Remove_K_Digits {
9
+ public String removeKdigits (String num , int k ) {
10
+ Stack <Character > stack = new Stack <>();
11
+ for (char digit : num .toCharArray ()){
12
+ while (k > 0 && !stack .isEmpty () && stack .peek () > digit ){
13
+ stack .pop ();
14
+ k --;
15
+ }
16
+ stack .push (digit );
17
+ }
18
+ for (int i = 0 ; i < k ; i ++) {
19
+ stack .pop ();
20
+ }
21
+ StringBuilder sb = new StringBuilder ();
22
+ while (!stack .isEmpty ()) {
23
+ sb .insert (0 , stack .pop ());
24
+ }
25
+ while (sb .length () > 1 && sb .charAt (0 ) == '0' ) {
26
+ sb .deleteCharAt (0 );
27
+ }
28
+ return (sb .length () == 0 ) ? "0" : sb .toString ();
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments