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;
}
相关推荐
smj2302_796826521 天前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode
sin_hielo1 天前
leetcode 1975
数据结构·算法·leetcode
2501_941820491 天前
面向零信任安全与最小权限模型的互联网系统防护设计思路与多语言工程实践分享
开发语言·leetcode·rabbitmq
cpp_25011 天前
P1583 魔法照片
数据结构·c++·算法·题解·洛谷
无限进步_1 天前
【C语言】堆排序:从堆构建到高效排序的完整解析
c语言·开发语言·数据结构·c++·后端·算法·visual studio
2501_941805931 天前
一次从接口网关到异步消息驱动架构演化的互联网系统实践技术随笔分享录
leetcode·决策树·贪心算法
黛色正浓1 天前
leetCode-热题100-二叉树合集(JavaScript)
javascript·算法·leetcode
水饺编程1 天前
下载和编译 VirtuaNES 模拟器源代码
c语言·c++·windows·visual studio
JAY_LIN——81 天前
数据在内存中的存储
c语言·开发语言
炽烈小老头1 天前
【每天学习一点算法 2026/01/05】打乱数组
学习·算法·leetcode