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;
}
相关推荐
多米Domi0116 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
方圆工作室6 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
Lips6117 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
今天_也很困8 小时前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
千金裘换酒9 小时前
LeetCode 数组经典题刷题
算法·leetcode·职场和发展
sycmancia10 小时前
C语言学习03——数据类型
c语言
alphaTao10 小时前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo10 小时前
leetcode 2943
数据结构·算法·leetcode
程序员-King.12 小时前
day134—快慢指针—环形链表(LeetCode-141)
算法·leetcode·链表·快慢指针
Swift社区12 小时前
LeetCode 376 摆动序列
算法·leetcode·职场和发展