前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode402. Remove K Digits

leetcode402. Remove K Digits

作者头像
眯眯眼的猫头鹰
发布2019-03-20 10:55:58
4590
发布2019-03-20 10:55:58
举报

题目要求

代码语言:javascript
复制
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个数字后能够得到的最小结果是多少?

思路和代码

直观的来说,删除数字得到最小的数字意味着我们应当尽可能的将越小的数字保留在高位,因此当我们从左往右遍历时,一旦遇到比前一个数字更小的数字,就应当删除前一个数字而保留这个数字。当我们用尽了所有删除时,就保留后面所有的数字,不再进行任何比较。因为我们已经尽可能获得了最小的最高位,因此无论后面的数字如何取值,其最高位上的数字一定是可以获得的最小的这个数字。举个例子:

代码语言:javascript
复制
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
第十步: 此时所有的删除次数用完,因此剩余的值全部保留

可以看到,当我们遇到较小值时,我们会尽可能的将其往左边移动,因为只要它比左边的值小且剩余删除次数,则删除左边的值一定会得到一个更小的值。

代码如下:

代码语言:javascript
复制
    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();
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-03-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档