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;
}
相关推荐
圣保罗的大教堂16 小时前
leetcode 3633. 最早完成陆地和水上游乐设施的时间 I 简单
leetcode
菜菜的顾清寒16 小时前
力扣HOT100(51) 动态规划-单词拆分
算法·leetcode·动态规划
Cloud_Shy61816 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第二章 Item 10 - 12)
c语言·开发语言·网络·人工智能·windows·python·编辑器
cpp_250116 小时前
P10109 [GESP202312 六级] 工作沟通
数据结构·c++·算法·题解·洛谷·gesp六级
ʚ希希ɞ ྀ16 小时前
全排列 --- 回溯
算法·leetcode·深度优先
水无痕simon16 小时前
9 C语言的基础练习
c语言·开发语言·算法
8Qi817 小时前
LeetCode 124. 二叉树中的最大路径和(Hard)
算法·leetcode·二叉树·递归
And_Ii17 小时前
LeetCode 1. 两数之和 python
数据结构·算法·leetcode
東隅已逝,桑榆非晚17 小时前
C语言预处理详解:从宏到条件编译
c语言·笔记·算法
cpp_250117 小时前
P10377 [GESP202403 六级] 好斗的牛
数据结构·c++·算法·题解·洛谷·gesp六级