-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path402. Remove K Digits.java
47 lines (47 loc) · 1.55 KB
/
402. Remove K Digits.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
46
47
class Solution {
public String removeKdigits(String s, int k) {
// if the length is to remove the equal length of s
// it is as good as "0" (returning the same)
if (s.length() == k)
return "0";
// stores into stack.
Stack<Character> stack = new Stack<>();
// iterate over the characters
for (char c : s.toCharArray()) {
while (!stack.isEmpty() && k > 0 && toInt(stack.peek()) > toInt(c)) {
// simply pop off
stack.pop();
k--;
}
stack.add(c);
}
/// while k is left
while (!stack.isEmpty() && k > 0) {
stack.pop();
k--;
}
// if (!stack.isEmpty()) == "0";
// StringBuilder to store the result
StringBuilder resultSb = new StringBuilder();
while (!stack.isEmpty()) {
resultSb.append(stack.pop());
}
// remove the left over zeros from front
while (resultSb.length() != 0 && resultSb.charAt(resultSb.length() - 1) == '0') {
resultSb.deleteCharAt(resultSb.length() - 1);
}
String res = resultSb.reverse().toString();
return res.equals("") ? "0" : res;
}
private int toInt(Character peek) {
// TODO Auto-generated method stub
return (int) (peek - '0');
}
}