[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();
    }
}

 

你可能感兴趣的:(Java)