C语言 | Leetcode C语言题解之第394题字符串解码

题目:

题解:

cpp 复制代码
#define N 2000

typedef struct {
    int data[30];;
    int top;
} Stack;

void push(Stack *s, int e) { s->data[(s->top)++] = e; }

int pop(Stack *s) { return s->data[--(s->top)]; }

//多位数字串转换成int
int strToInt(char *s)
{
    char val[] = {'\0', '\0', '\0', '\0'};
    int result = 0;

    for(int i = 0; isdigit(s[i]); ++i)
        val[i] = s[i];
    
    for(int i = strlen(val) - 1, temp = 1; i >= 0; --i, temp *= 10)
        result += ((val[i] - '0') * temp);
    
    return result;
}

char* decodeString(char *s)
{
    Stack magnification; magnification.top = 0;
    Stack position; position.top = 0;

    char *result = (char*)malloc(sizeof(char) * N);
    char *rear = result;

    for(int i = 0; s[i] != '\0'; ) {
        if(isdigit(s[i])) {
            push(&magnification, strToInt(&s[i]));

            while(isdigit(s[i]))
                ++i;
        }

        else if(s[i] == '[') {
            push(&position, rear - result);
            ++i;
        }

        else if(s[i] == ']') {
            char *p = result + pop(&position);
            int count = (rear - p) * (pop(&magnification) - 1);

            for(; count > 0; --count)
                *(rear++) = *(p++);
            
            ++i;
        }

        else
            *(rear++) = s[i++];
    }

    *rear = '\0';
    return result;
}
相关推荐
Shylock_Mister6 分钟前
ARM与x86交叉编译实战排错指南
linux·c语言·arm开发
高山有多高1 小时前
堆应用一键通关: 堆排序 +TOPk问题的实战解析
c语言·数据结构·c++·算法
1白天的黑夜11 小时前
递归-二叉树中的剪枝-814.二叉树剪枝-力扣(LeetCode)
c++·leetcode·剪枝·递归
程序猿追1 小时前
Ascend C编程范式总结:与CUDA的异同对比
c语言·开发语言·算法
前进之路92 小时前
Leetcode每日一练--47
数据结构·算法·leetcode
晨非辰3 小时前
【数据结构初阶系列】归并排序全透视:从算法原理全分析到源码实战应用
运维·c语言·数据结构·c++·人工智能·python·深度学习
松涛和鸣8 小时前
11.C 语言学习:递归、宏定义、预处理、汉诺塔、Fibonacci 等
linux·c语言·开发语言·学习·算法·排序算法
Miraitowa_cheems10 小时前
LeetCode算法日记 - Day 106: 两个字符串的最小ASCII删除和
java·数据结构·算法·leetcode·深度优先
小白程序员成长日记10 小时前
2025.11.12 力扣每日一题
算法·leetcode·职场和发展
未若君雅裁11 小时前
LeetCode 51 - N皇后问题 详解笔记
java·数据结构·笔记·算法·leetcode·剪枝