第三周OJ-Q402解题方法

问题

Remove K Digits

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.


解决思路

解决这个问题,可以这么想,每次我要删除一个数字,一定是要比之前的状态要好,并且要将抽取之后的取值降到最小。然后就是要做遍历。首位当然直接取出,存在数组中作为输出时的来源。然后往下走,在遍历过程中,如果发现当前数字比之前取出的小,那删除掉已经取出的较大数显然可以在最后获得一个更小的数,然后从输出的数组末尾比起,依次删到不能删除为止。最后得到的输出数组再把头部的0整一整即可。代码如下:

class Solution {
public:
    string removeKdigits(string num, int k) {
        int l = num.length()-k;
        char s[num.length()];
        char cs[num.length()];
        strcpy(cs,num.c_str());
        int index = 0;  
        for(int i = 0;i<num.length();i++){
            int current = cs[i];  
            while(index>0&&current<s[index-1]&&k>0){
                index–;
                k–;
            }
            s[index++] = current;
        }
        int _index = 0;
        while (_index < l && s[_index] == ‘0’){
            _index++;
             
        }
        if(_index == l){
            return “0”;
        }
        else{
            string result = “”;
            for(int i =_index;i<l;i++){
                result=result+s[i];
            }
            return result;
             
        }
         
    }
};


点赞