402. 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个数字,已知一个字符串表示的非负整数num,将num中的K个数字移除,求移除K个数字后,可以获得的最小的数字。

    分析:若去掉某一位数字,为了使得到的新数字最小,需要尽可能的让新数字优先最高位最小,其次次高位最小,以此类推。所以,从高位向低位遍历,如果对应的数字大于下一位数字,则把该位数字去掉,得到的数字最小

    算法:使用存储最终结果,从高位向低位遍历num,如果遍历的数字大于栈顶元素,则将该数字入栈,如果小于栈顶元素则栈顶元素出栈,直到栈为空(size==0)或者不能再删除数字(k==0)或者栈顶小于当前元素为止。由于最后需要输出字符串,我们用vector模拟栈的后进先出效果,并遍历vector得到最终的字符串。

    思考:当所有数字都扫描完成后,K仍然>0,应该做怎样的处理?当数字中有0出现时,应该有怎样的处理?

class Solution {
public:
  string removeKdigits(string num, int k) {
	if (num.size() <= k)
		return "0";

	vector<char> log;
	int pos = 0;
	while (pos < num.size())
	{
		if (num[pos] != '0' || !log.empty())
		{
			log.push_back(num[pos]);
		}
		pos++;
		while(k>0 && !log.empty() &&num[pos] < log[log.size()-1])
		{
			log.pop_back();
			k--;
		}	
	}

	while (k > 0)
	{
		log.pop_back();
		k--;
	}

	string result;
	for (int i = 0; i < log.size(); i++)
	{
		result += log[i];
	}
	if (result == "")
		result = "0";
	return result;

}
};

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值