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个数后的所组成的最小数值。
思路一:通过回溯算法,找出len-k个数组成的最小数,最后一个用例会TLE,程序如下:
扫描二维码关注公众号,回复:
1947614 查看本文章
class Solution {
int min = Integer.MAX_VALUE, cur = 0;
public String removeKdigits(String num, int k) {
backTracing(num, num.length(), num.length() - k, 0);
return String.valueOf(min);
}
public void backTracing(String num, int len, int k, int begin){
if (begin > len){
return;
}
if (k == 0){
min = Math.min(min, cur);
return;
}
for (int i = begin; i < len; ++ i){
cur = cur*10 + num.charAt(i) - '0';
backTracing(num, len, k - 1, i + 1);
cur = (cur - num.charAt(i) + '0')/10;
}
}
}
思路2:通过DP求解,利用栈来实现,程序如下所示:
class Solution {
public String removeKdigits(String num, int k) {
ArrayDeque<Character> stack = new ArrayDeque<>();
int len = num.length();
for (int i = 0; i < len; ++ i){
while (k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(i)){
stack.pop();
k --;
}
stack.push(num.charAt(i));
}
while (k > 0){
stack.pop();
k --;
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()){
sb.append(stack.pop());
}
String s = sb.reverse().toString();
len = s.length();
for (int i = 0; i < len; ++ i){
if (s.charAt(i) != '0'){
return s.substring(i, len);
}
}
return "0";
}
}