https://leetcode.com/problems/remove-k-digits/
删除k个数,使得剩余的数值最小
贪心,当前遍历的char如果比数组的最后一位小,则数组最后一位前移(相当于删除最后一位),直到当前char大于等于数组最后一位,当然边界条件top和k也是很重要的。
public class Solution {
public String removeKdigits(String num, int k) {
char[] arr = new char[num.length()];
int top = 0;
int digit = num.length() - k;
for (int i = 0; i < num.length(); i++) {
char c = num.charAt(i);
while (top > 0 && arr[top - 1] > c && k > 0) {
k--;
top--;
}
arr[top++] = c;
}
int count = 0;
while (count < digit && arr[count] == '0') {
count++;
}
return count == digit ? "0" : new String(arr, count, digit - count);
}
}