Leetcode-Remove K Digits

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 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.

explain

题意是从该字符串中删除K位字符,使得结果是最小的。一般看到最小的,如果不想暴力的做的话,要用贪婪的策略。我这里给到的方法,就是把前一个比后一个大的数删除,这样一趟下来,位比较前,又比较大的数会被删掉。如果一趟遍历,删除的位数不足,观察样例,是要把从后面把剩余的K位剔除。剔除后,如果字符串的第一位是0,还得继续剔除首位0的情况。因此,整个答案就出来。

solution

class Solution {
public:
    string removeKdigits(string num, int k) {
        int len = num.length();
        if (len <= k) return "0";
        
        string res = "";
        for (int i = 0; i < num.length(); i++) {
            while (k != 0 && !res.empty() && num[i] < res.back()) {
                res.pop_back();
                k--;
            }
            res.push_back(num[i]); 
        }
        if (k) res = res.substr(0, res.length() - k);
        while(!res.empty() && res[0] == '0') res.erase(res.begin());
        if (res.empty()) return "0";
        else return res; 
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容