Leetcode:402. Remove K Digits (Week 7)

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.

解題思路及算法分析

本題是medium,比較麻煩的是要弄清楚其規律,很容易遺漏0的情況。考慮怎麼解決,就要先弄清楚去數規律:比如去k個數字,要是前k個裏面包含0,那麼就要把0留下,最後自動去除;若沒有0,要去的這個數,一定是從左到右,第一次比它後面的那個數字大的數字,但是若數字是非遞減的,則去掉後面最大的數字保留第一數的數即可。醬紫就可以解決所有情況,包括是0的情況。
注意:最後輸出結果的時候要去掉前面的0。

代碼

class Solution {
public:
    string removeKdigits(string num, int k) {
        int n = num.size();
        if(k >= n) return "0";
        while(k) {
            int i = 0;
            bool flag = false;
            for (i = 0; i<num.size(); i++) {
                if(num[i] > num[i+1]) {
                    flag = true;
                    num = num.erase(i,1);
                    break;
                }
            }
            if(flag == false) {
                num = num.substr(0,num.size()-1);
            }
            k--;
        }
        while(num.size() > 1 && num[0] == '0') {
            num = num.substr(1);
        }
        return num;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章