-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13-RemoveKDigits.java
31 lines (27 loc) · 957 Bytes
/
13-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
class Solution {
public String removeKdigits(String num, int k) {
LinkedList<Character> stack = new LinkedList<Character>();
for (char digit : num.toCharArray()) {
while (stack.size() > 0 && k > 0 && stack.peekLast() > digit) {
stack.removeLast();
k -= 1;
}
stack.addLast(digit);
}
/* remove the remaining digits from the tail. */
for (int i = 0; i < k; ++i) {
stack.removeLast();
}
// build the final string, while removing the leading zeros.
StringBuilder ret = new StringBuilder();
boolean leadingZero = true;
for (char digit : stack) {
if (leadingZero && digit == '0') continue;
leadingZero = false;
ret.append(digit);
}
/* return the final string */
if (ret.length() == 0) return "0";
return ret.toString();
}
}