LeetCode: Remove K Digits

来源:互联网 发布:广电总局网络主播新规 编辑:程序博客网 时间:2024/06/05 19:58

题目:
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.

题目要求在给定数字字符串num中删除k个字符,使字符串表示的数字最小。

用贪心法来解:
因为数字开头不允许是0,当第二位是0的情况下,如果我们删除了第一位数,那么连通第二位也被删除,至少可以使数字小两个量级。而其他位置最多也就是小一个数量级,所以这种情况毫无疑问先删除第一个数。
当只能删除一个量级时,从头开始找,找到第一个下降的数并删除。如 1234553,那么最后一个3前面的5就是,删除它得到的数字是最小的。

算法还需要特别注意几种情况,一是整串数字递增时,删去最末尾的数字;二是每删去一个数字,都要对开头的数字去零,有可能第一位后面连着若干个0(具体数量不可知),删除第一位时不可能显式地将所有0删除;三是每删去一个数字,都要判断字符串是否为空,空表示0,如果为空,将“0”赋给字符串。
Accepted的代码:

class Solution {public:    string removeKdigits(string num, int k) {        while(k--)        {            //如果第二位是0,那么先将第一位删去            if(num[1]=='0')                 num.erase(num.begin(),num.begin()+2);            else            {                int i;                bool mark=false;                for(i=0;i<num.length()-1;i++)                {                    //删去第一个下降的数                    if(num[i]>num[i+1])                    {                        num.erase(num.begin()+i);                        if(i==num.length()-1) mark=true;                        break;                    }                }                //最后一个数字最大                if(i==num.length()-1&&mark==false) num.erase(num.begin()+num.length()-1);            }            //去除开头的0            while(num[0]=='0') num.erase(num.begin());            //如果结果等于0            if(num.length()==0)            {                num="0";                break;            }        }        return num;    }};
0 0
原创粉丝点击