402. Remove K Digits

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位后尽可能得到最小值

 1     public String removeKdigits(String num, int k) {
 2         Stack<Character> digs = new Stack<>();
 3         int length = num.length();
 4         if (k == 0) return num;
 5         if (k == length) return "0";
 6         int i = 0;
 7         while (i < length) {
 8 
 9             while (k > 0 && !digs.isEmpty() && num.charAt(i) < digs.peek()) {
10                 //保证顶上的元素小于等于num.charAt(i)
11                 digs.pop();
12                 k--; //相当于删除一位较大的值
13             }
14             digs.push(num.charAt(i));//保证栈从顶到低的值是递减的
15             i++;
16         }
17         while (k > 0) { //k为数字还没有删除够,继续删除
18             digs.pop();
19             k--;
20         }
21         StringBuilder sb = new StringBuilder();
22         while (!digs.isEmpty()) {
23             sb.append(digs.pop()); //构成由高到底的字符串
24         }
25         sb.reverse();//翻转成由底到高的字符串,因为在push的时候是按照i顺序push的,所以反转后的字符串中每个字符的先后顺序和原来保持一致
26         while (sb.length() > 1 && sb.charAt(0) == '0') {
27             sb.deleteCharAt(0);
28         }
29         return sb.toString();        
30     }
 
原文地址:https://www.cnblogs.com/wzj4858/p/7726044.html