Leetcode刷题98-402. 移掉K位数字(C++详细解法!!!)

本文介绍了如何解决LeetCode上的移除K位数字问题,使用C++编程语言,通过贪心算法实现。文章分析了算法思路,包括特殊情况的处理,如数字0的出现和k仍有剩余的情况,并提供了AC代码。
摘要由CSDN通过智能技术生成

Come from : [https://leetcode-cn.com/problems/remove-k-digits/]

1.Question

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:

1. The length of num is less than 10002 and will be ≥ k.
2. 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.

2.Answer

meduim 类型题目。贪心算法。
算法分析

  1. 使用存储最终结果或删除工作,从高位向低位遍历num。
  2. 如果遍历的数字大于栈顶元素,则将该数字push入栈
  3. 如果小于栈顶元素则进行pop弹栈,知道栈为空或者不能删除数字(k==0)或栈顶小于当前元素为止。

弹出示例:
在这里插入图片描述

思考,需要特殊处理的部分:(特殊处理的部分全部在AC代码中给出)

  1. 当所有数字都扫描完成后,k仍然>0,应该如何处理?比如:num=12345,k=3时
  2. 当数字中有0出现,应该有怎样的特殊处理?比如:num=100200,k=0时
  3. 如何将最后结果存储为字符串并返回?
    AC代码如下:
class Solution {
   
public:
    string removeKdigits(string num, int k) {
   
        vector<int> S;
        string result = "";     //存储最终结果
        for(int i = 0; i < num.length(); ++i)
        {
   
            int number = num[i] - '0'; 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值