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; 
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容