6. Remove K Digits

Link to the problem

Description

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

Input: num = "1432219", k = 3, Output: "1219"
Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Input: num = "10200", k = 1, Output: "200"
Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Input: num = "10", k = 2, Output: "0"
Remove all the digits from the number and it is left with nothing which is 0.

Idea

Greedy algorithm works in this case. Suppose x > y, and we want to remove one digit from x, then we can move the same digit in y, and get x' >= y'. Hence, it never hurts to remove one digit which make the number smallest.
To remove a single digit to make the remaining number smallest, we remove the first digit, whose right neighbor is strictly smaller than itself.

Solution

class Solution {
private:
    string removeOneDigit(string num) {
        int index = 0;
        while (index < num.size() - 1 && num[index + 1] >= num[index]) {
            index++;
        }
        return num.substr(0, index) + num.substr(index + 1);
    }
public:
    string removeKdigits(string num, int k) {
        for (int i = 0; i < k; i++) {
            num = removeOneDigit(num);
        }
        int index = 0;
        while (index < num.size() && num[index] == '0') index++;
        num = num.substr(index);
        if (num.empty()) num = "0";
        return num;
    }
};

Performance

33 / 33 test cases passed.
Runtime: 16 ms

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,350评论 0 33
  • 今天去了健身房 虽然听起来没什么 但是在这个人生地不熟的城市 只是凭着一张美团单次健身卡就踏上旅程 坐着没做过的公...
    神投手阅读 1,189评论 2 1
  • 今日早餐,主角:扯面条,配角:葡萄、牛奶、玫瑰花花 叨叨念:在北方的大城小城里,总会找到各种各样的面馆,卖着各式各...
    樱樱小香阅读 3,355评论 2 4
  • 今天给大家分享一下个人关于镜子理论的看法 1 你亲手创造了你的世界 你希望它是什么样的,它将会往你希望的方向走, ...
    滔Roy阅读 6,549评论 0 46