Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
- The length of num is less than 10002 and will be ≥ k.
- The given num does not contain any leading zero.
Example 1:
Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.
思路:
首先考虑只删除一个数的情况。删除一个数字,结果都是总位数减少一位,在剩下相同位数的整数里,优先把高位的数字降低,对新整数的值影响最大。
遍历原整数,从左到右进行比较,如果某一位的数字大于它右边的数字,说明删除该数字后会使该数位的值降低。
每一步都找出删除一个数后的最小值,重复k次,结果就是删除k个数的最小值。(局部最优->全局最优)
注意: 用k作为外循环,遍历数字作为内循环的话时间复杂度太高。应把k作为内循环.
detail:遍历原整数的时候,用一个stack,让每数字入栈,当某个数字需要被删除时让它出栈即可。最后返回由栈中数字构成的新整数
因为可能栈的第一个元素为0,最后要再遍历一下栈中的元素,找到第一个非0的index。手动写一个由数组构成的stack更方便。
时间:O(N),空间:O(N)
class Solution { public String removeKdigits(String num, int k) { int len = 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(k > 0 && top > 0 && stack[top-1] > c) { top -= 1; k -= 1; } stack[top++] = c; } int idx = 0; while(idx < len && stack[idx] == '0') idx++; return idx == len ? "0" : new String(stack, idx, len - idx); } }