402. Remove K Digits

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.

这题思路很好想,因为不能改变相对位置关系,所以我们可以根据剩下的数字长度,从高位到低位检索。比如,总长度为5的情况下,如果删除两位还剩三位,那么最高位必须是在前三个数字中,所以找出最小的那个就行,依次类推,可以用迭代也可以用递归。代码如下:

方法一:

string removeKdigits(string num, int k) {
    string res;
    helper(num, k, res);
    return res;
}
void helper(string num, int k, string& res) {
    if (k == num.size()) {
        if (res.size() == 0) res = "0";
        return;
    }
    if (k == 0) {
        res += num;
        if (res.size() == 0) res = "0";
        return;
    }
    int minid = 0;
    for (int i = 0; i <= k; i++) {
        if (num[i] < num[minid]) minid = i;
    }
    if (res.size() != 0 || num[minid] != '0') res += num[minid];
    helper(num.substr(minid+1, num.size()-minid-1), k-minid, res);
    return;
}

方法二:

还有个比较适用的规律就是,从原数字的高位到低位检索,删除第一个下降的数字,然后又从头开始检索,依次删除K次,因为每删除一次数量级固定下降一位,所以如果是后一位比这一位大,删除这一位那么后一位更大的数就会在比较高的数量级上,但如果后一位更小的话,就会让小的数到高位上来。所以按照这个规律,最后在注意一下去掉开头的0,就可以得到结果。

string removeKdigits(string num, int k) {
    if (num.size() <= k) return "0";
    for (int i = 0; i < k; i++) {
        for (int j = 0; j < num.size(); j++) {
            if (j == num.size()-1 || num[j] > num[j+1]) {
                num = removeOne(num, j);
                break;
            }
        }
    }
    while (num[0] == '0') num = removeOne(num, 0);
    if (num.size() == 0) return "0";
    return num;
}
string removeOne(string & num, int pos) {
    return num.substr(0, pos) + num.substr(pos+1, num.size()-pos-1);
}

你可能感兴趣的:(leetcode)