faster than 88.79% of Java online submissions for Remove K Digits.
public class Solution {
public String removeKdigits(String num, int k) {
int newLength = num.length() - k;
char[] stack = new char[num.length()];
int top = 0;
for (int i = 0; i < num.length(); i++) {
char c = num.charAt(i);
//此处while不能改为if
//比如:561
while (k > 0 && top > 0 && stack[top - 1] > c) {
top--;
k--;
}
stack[top++] = c;
}
int offset = 0;
while (offset < newLength && stack[offset] == '0') {
offset++;
}
//new String(stack, offset, newLength - offset)
//是为了在递增的情况下进行截取,如1234567
return offset == newLength ? "0" : new String(stack, offset, newLength - offset);
}
}