-
Notifications
You must be signed in to change notification settings - Fork 1
/
RemoveKDigits.java
45 lines (39 loc) · 1.07 KB
/
RemoveKDigits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.Stack;
// https://leetcode.com/problems/remove-k-digits/
public class RemoveKDigits {
private final String num;
private int k;
public RemoveKDigits(String num, int k) {
this.num = num;
this.k = k;
}
public String solution() {
if (num.length() == k) {
return "0";
}
Stack<Character> stack = new Stack<>();
int i = 0;
while (i < num.length()) {
while (k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(i)) {
stack.pop();
k--;
}
stack.push(num.charAt(i));
i++;
}
while (k > 0) {
stack.pop();
k--;
}
var result = new StringBuilder();
while (!stack.isEmpty()) {
result.append(stack.pop());
}
result.reverse();
while (result.length() > 1 && result.charAt(0) == '0') {
result.deleteCharAt(0);
}
return result.toString();
}
}