leetcode402. Remove K Digits

4次阅读

共计 1623 个字符,预计需要花费 5 分钟才能阅读完成。

题目要求
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 个数字后能够得到的最小结果是多少?
思路和代码
直观的来说,删除数字得到最小的数字意味着我们应当尽可能的将越小的数字保留在高位,因此当我们从左往右遍历时,一旦遇到比前一个数字更小的数字,就应当删除前一个数字而保留这个数字。当我们用尽了所有删除时,就保留后面所有的数字,不再进行任何比较。因为我们已经尽可能获得了最小的最高位,因此无论后面的数字如何取值,其最高位上的数字一定是可以获得的最小的这个数字。举个例子:
10200 k=1
第一步:0 和 1 比较,此时 0 比 1 小,且还有一次可用的删除,因此删除 1,保留 0
第二步:因为无可用的删除次数,因此剩下的值全部保留

123450123 k=5
第一步:2>1 保留
第二步:3>2 保留
第三步: 4>3 保留
第四步: 5>4 保留
第五步:0<5 删除 5 保留 0 k=4
第六步: 0<4 删除 4 保留 0 k=3
第七步:0<3 删除 3 保留 0 k=2
第八步:0<2 删除 2 保留 0 k=1
第九步:0<1 删除 1 保留 0 k=0
第十步: 此时所有的删除次数用完,因此剩余的值全部保留
可以看到,当我们遇到较小值时,我们会尽可能的将其往左边移动,因为只要它比左边的值小且剩余删除次数,则删除左边的值一定会得到一个更小的值。
代码如下:
public String removeKdigits(String num, int k) {
if(num == null || num.length() == 0 || k==num.length()) return “0”;
Stack<Character> stack = new Stack<>();
for(int i = 0 ; i < num.length() ; i++) {
char c = num.charAt(i);
while(k> 0 && !stack.isEmpty() && stack.peek() > c) {
stack.pop();
k–;
}
stack.push(c);
}

while(k > 0) {
stack.pop();
k–;
}

StringBuilder result = new StringBuilder();
while(!stack.isEmpty()) {
result.append(stack.pop());
}
while(result.length() > 1 && result.charAt(result.length()-1) == ‘0’) {
result.deleteCharAt(result.length()-1);
}
return result.reverse().toString();
}

正文完
 0