Java implementation LeetCode 402 K definite displacement digit

402. definite displacement K-digit

Given a non-negative integer num as a string, removing the k-bit digital numbers such that the minimum remaining figures.

note:

num is less than 10002 and a length of ≥ k.
num does not contain any leading zeros.
Example 1:

Input: num = "1432219", k = 3
Output: "1219"
explanation: the number 4 is removed out of three, 3, 2, and form a new minimum number 1219.
Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: the first definite displacement of the remaining output number 1 to 200. Note that there can be no leading zeros.
Example 3:

Input: num = "10", k = 2
Output: "0"
explanation: remove all numbers from the original figures, the remaining blank is 0.

class Solution {
    public String removeKdigits(String num, int k) {
        if (num == null || num.length() == 0) {
            return num;
        }
        int length = num.length();
        if (k <= 0 || k > length) {
            return num;// 非法
        }
        if (k == length) {
            return "0";
        }

        char[] chars = num.toCharArray();

        char[] newChars = new char[length]; // 移除k个数字的结果
        int newCharsTop = 0;
        for (int i = 0; i < length; i++) {
            while (k > 0 && newCharsTop > 0 && newChars[newCharsTop - 1] > chars[i]) {
                newCharsTop--;
                k--; // 移除一个数字
            }
            newChars[newCharsTop] = chars[i];
            newCharsTop++;
        }
        if (k > 0) { // 从后面移除k个数字
            newCharsTop = newCharsTop - k;
            k = 0;
        }

        // 起始位置不能是0
        int startIndex = 0;
        while (newChars[startIndex] == '0' && startIndex < newCharsTop) {
            startIndex++;
        }
        // 从起始位置返回  newCharsTop - startIndex
        if (newCharsTop - startIndex > 0) {
            return new String(newChars, startIndex, newCharsTop- startIndex);
        }

        return "0";
    }
}
Released 1530 original articles · won praise 20000 + · views 2.08 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104851551