C语言 | Leetcode C语言题解之第402题移掉K位数字

题目:

题解:

cpp 复制代码
char* removeKdigits(char* num, int k) {
    int n = strlen(num), top = 0;
    char* stk = malloc(sizeof(char) * (n + 1));
    for (int i = 0; i < n; i++) {
        while (top > 0 && stk[top] > num[i] && k) {
            top--, k--;
        }
        stk[++top] = num[i];
    }
    top -= k;

    char* ans = malloc(sizeof(char) * (n + 1));
    int ansSize = 0;
    bool isLeadingZero = true;
    for (int i = 1; i <= top; i++) {
        if (isLeadingZero && stk[i] == '0') {
            continue;
        }
        isLeadingZero = false;
        ans[ansSize++] = stk[i];
    }
    if (ansSize == 0) {
        ans[0] = '0', ans[1] = 0;
    } else {
        ans[ansSize] = 0;
    }
    return ans;
}
相关推荐
老王爱玩车12 小时前
深入理解指针5
c语言·开发语言·学习
Navigator_Z12 小时前
LeetCode //C - 1275. Find Winner on a Tic Tac Toe Game
c语言·算法·leetcode
All for pursuit.14 小时前
【分治-2】215.数组中的第K个最大元素
数据结构·c++·算法·leetcode
blxr_15 小时前
力扣hot100前k个高频元素https://leetcode.cn/problems/top-k-frequent-elements/
算法·leetcode·职场和发展
朔北之忘 Clancy1 天前
2025 CSP-J 第二轮真题解析
c++·青少年编程·题解·noip·csp·信奥赛·noi
longlongzihan1 天前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
铅笔小新z1 天前
【C语言】操作符
c语言
by209991 天前
从 malloc/free 到 new/delete:真正理解 C++ 中的内存管理与对象生命周期
c语言·c++·经验分享·动态内存管理
额额额对了1 天前
SPI通信
linux·c语言·汇编·单片机·嵌入式硬件·arm
王老师青少年编程1 天前
2026年9月GESP真题及题解(C++七级):括号序列
题解·真题·gesp·csp·c++七级·括号序列·2026年9月