美文网首页Leetcode
Leetcode-Remove K Digits

Leetcode-Remove K Digits

作者: Juliiii | 来源:发表于2017-10-04 19:33 被阅读0次

    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; 
        }
    };
    

    相关文章

      网友评论

        本文标题:Leetcode-Remove K Digits

        本文链接:https://www.haomeiwen.com/subject/cqpcyxtx.html