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;
}
相关推荐
坚持编程的菜鸟8 小时前
模拟实现memmove
c语言·算法·模拟实现memmove
坚持编程的菜鸟10 小时前
编写判断大小端程序
c语言·算法·判断大小端
不负岁月无痕11 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
qq_4480111611 小时前
C语言中的指针函数和函数指针
java·c语言·开发语言
clerly12 小时前
C语言如何实现继承?
c语言·多态·继承·封装·结构体
wengqidaifeng13 小时前
2026 年电赛(TI 杯)H 题:MaxiCamPro、双主控通信、VOFA+ 遥测与可复现实验方法
c语言·单片机·嵌入式硬件
evans在进步13 小时前
LeetCode 2 两数相加:链表模拟加法,Java 图解进位过程
java·leetcode·链表
Hi李耶14 小时前
【LeetCode】557.反转字符串中的单词 III
算法·leetcode·职场和发展
c2385615 小时前
C/C++每日一练20
c语言·开发语言·c++
坚持编程的菜鸟15 小时前
模拟实现strncpy
c语言·算法·模拟实现strncpy