[Leetcode] 402. Remove K Digits 解题报告

本文介绍了一种使用贪心算法解决从给定数字中移除k位使其成为可能的最小数值的问题。通过扫描字符串并利用栈的思想进行比较和移除,确保最终结果是最小值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

思路

贪心算法:扫描一遍字符串,如果当前字符比结果字符串的最后一个字符要小,并且还可以再删除,那么就删除结果字符串的最后一个字符,直到没有可以删除的字符,就将当前字符加入结果字符串中。怎么分析时间复杂度呢?由于每个字符最多在while循环中被弹出一次,所以for循环中的while循环最多也就执行O(n)次,因此总的时间复杂度仍然是O(n)。空间复杂度也是O(n)(因为临时结果集中有可能需要存贮额外的字符)。

这道题目理论上是用stack来解答的,虽然我下面的代码没有采用stack,但是实际上是用vector来模拟stack了^_^(STL中的string是用vector来做底层表示的)。

代码

class Solution {
public:
    string removeKdigits(string num, int k) {
        string ans;
        int n = k, len = num.size(), cnt = 0;
        for(auto val : num) {
            while(!ans.empty() && n > 0 && val < ans.back()) {
                --n;
                ans.pop_back();
            }
            ans.push_back(val);
        }
        while(ans[cnt] == '0') {
            cnt++;
        }
        ans = ans.substr(cnt, len - k - cnt);
        return ans.size() > 0 ? ans : "0";
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值