leetcode 402. 移掉K位数字

该博客讨论了一种算法问题,即如何从一个非负整数中移除K位数字,使得剩下的数字最小。提供的解决方案包括C++和Python代码实现,通过比较数字并维护一个最小堆来实现这一过程。示例展示了如何处理带有前导零的情况,并确保结果不包含前导零。
摘要由CSDN通过智能技术生成

给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。

注意:

num 的长度小于 10002 且 ≥ k。
num 不会包含任何前导零。

示例 1 :

输入: num = "1432219", k = 3
输出: "1219"
解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。

示例 2 :

输入: num = "10200", k = 1
输出: "200"
解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。

示例 3 :

输入: num = "10", k = 2
输出: "0"
解释: 从原数字移除所有的数字,剩余为空就是0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-k-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:
    string removeKdigits(string num, int k) {
        vector<char> ans;
        for (auto & digit: num) {
            while(ans.size() > 0 && ans.back() > digit && k) {
                ans.pop_back();
                k -= 1;
            }
            ans.push_back(digit);
        }

        for (; k > 0; k--) {
            ans.pop_back();
        }
        string res = "";
        bool isLeadingZero = true;
        for (auto & digit: ans) {
            if (isLeadingZero && digit == '0') {
                continue;
            }
            isLeadingZero = false;
            res += digit;
        }
        return res == "" ? "0" : res;
    }
};
class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        ans = []

        for digit in num:
            while k and ans and ans[-1] > digit:
                ans.pop()
                k -= 1
            ans.append(digit)
        res = ans[:-k] if k else ans
        return "".join(res).lstrip('0') or "0"
char * removeKdigits(char * num, int k){
    int n = strlen(num);
    int top = 0;
    char *ans = malloc(sizeof(char) * (n + 1));
    for (int i = 0; i < n; i++) {
        while (top > 0 && ans[top] > num[i] && k) {
            top--;
            k--;
        }
        ans[++top] = num[i];
    }
    top -= k;

    char *res = malloc(sizeof(char) * (n + 1));
    int resSize = 0;
    bool isLeadingZero = true;
    for (int i = 1; i < top + 1; i++) {
        if (isLeadingZero && ans[i] == '0') {
            continue;
        }
        isLeadingZero = false;
        res[resSize++] = ans[i];
    }

    if (resSize == 0) {
        res[0] = '0';
        res[1] = '\0';
    }
    else {
        res[resSize] = '\0';
    }

    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值