Leetode402. Remove K Digits

本文介绍了解决LeetCode 402题的方法,该题要求从一个非负整数中移除k位数字,使剩下的数字尽可能小。通过逐位检查并移除首位递减的数字来实现最小化。

LeetCode402. 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.

思路

从原数字的高位到低位检索,删除第一个下降的数字,然后又从头开始检索,依次删除K次,因为每删除一次数量级固定下降一位,所以如果是后一位比这一位大,删除这一位那么后一位更大的数就会在比较高的数量级上,但如果后一位更小的话,就会让小的数到高位上来。所以按照这个规律,最后在注意一下去掉开头的0,就可以得到结果。

代码实现

class Solution {
public:
    string remove(string & num, int pos) {
    return num.substr(0, pos) + num.substr(pos+1, num.size()-pos-1);
   }

    string removeKdigits(string num, int k) {

        if(num.size()<=k) return "0";

        for(int i=0; i<k; i++){
            for(int j=0; j<num.size(); j++){
                if(j==num.size()-1 || num[j]>num[j+1]){
                    num=remove(num,j);
                    break;
                }
            }
        }

        while(num[0]=='0') num=remove(num,0);
        if (num.size() == 0) return "0";//num="10",k=1的情况
        return num;
    }
};

ps: substr()函数

basic_string substr(size_type _Off = 0,size_type _Count = npos) const;
参数
_Off
所需的子字符串的起始位置。字符串中第一个字符的索引为 0,默认值为0.
_Count
复制的字符数目

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值