C++ algorithm learning (Likou: 402. Remove K digits)

Given a non-negative integer num represented by a string, remove k digits from this number to make the remaining number the smallest.

note:

The length of num is less than 10002 and ≥ k.
num will not contain any leading zeros.
Example 1:

输入: num = "1432219", k = 3
输出: "1219"
解释: 移除掉三个数字 4, 3,2 形成一个新的最小的数字 1219

Example 2:

输入: num = "10200", k = 1
输出: "200"
解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零

.
Example 3:

输入: num = "10", k = 2
输出: "0"
解释: 从原数字移除所有的数字,剩余为空就是0

Source: LeetCode
Link: https://leetcode-cn.com/problems/remove-k-digits
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Personal problem-solving process:
This kind of diagram is very simple at first glance, 1432219, you need to delete a number, if you delete 1, it is 432219, which is the beginning of 4, if you delete 4, it is the beginning of 1, and it must be deleted 4 not 1 Let's take a look at 4 and 3. If you delete 4, it will start with 13, and if you delete 3, it will start with 14. This kind of question must start with the smaller the better. Then delete 4 or 2 later, I believe there is no confusion. Then the rule is here. First delete the high-order bits. To be specific, we come to a conclusion that we start traversing from the high-order bits. If the left side is larger than the right side, delete the left number.

class Solution {
    
    
public:
    string removeKdigits(string num, int k) {
    
    
    //先判断字符串长度小于等于k的时候不禁删,我直接返回的0可能题目设置有问题,我感觉小于的时候应该返回""
        if(num.size()<=k) return "0";
     //开始一次k循环删一个
    for(;k>0;k--){
    
    
    for(int i=0;i<num.size();i++)
        if(num[i]>num[i+1]){
    
    
            for(int j=i;j<num.size()-1;j++)
                num[j]=num[j+1];
            break;
        }
    num.pop_back();
    }
    //开头有0删了
    while(num.size()>1 && num[0] == '0'){
    
    
        for(int j=0;j<num.size()-1;j++)
                num[j]=num[j+1];
         num.pop_back();
    }
        return num;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45743162/article/details/109704184