[Leetcode学习-java]Remove K Digits(去掉K个数字)

问题:

难度:easy

说明:

输入一个字符串,去掉其中K个字符,剩下的字符刚好组成最小的数字。

输入范围:

// 10002长度,而且num长度大于等于K,string都是0~9字符
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个字符,num.length - K剩下的为低位,低位不用理用回string里面的低位就行,主要是高位(进位最多的)都需要拿到最小的一个数。

class Solution {
    public String removeKdigits(String num, int k) {
        // high index
        int hi = 0;
        // 最好转成数组,charAt效率会在数据量大时候运行时间长
        char[] tempchs = num.toCharArray();
        StringBuilder builder = new StringBuilder();

        int len = num.length();
        for(int i = 0;i < len; i ++) {
            char c = tempchs[i];
            // 发现低位是更小就往高位挪,而且k位以内的距离限制
            while(k > 0 && hi > 0 && tempchs[hi - 1] > c) {
                hi --;
                k --;
            }

            tempchs[hi ++] = c;
        }

        boolean trim = false;
        // cut length
        int cl = hi - k;
        for(int i = 0;i < cl;i ++) {
            // 先进行去0
            if((!trim && tempchs[i] == '0')) continue;
            trim = true;
            builder.append(tempchs[i]);
        }

        return builder.length() == 0 ? "0" : builder.toString();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值