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;
}
相关推荐
sycmancia44 分钟前
C语言学习03——数据类型
c语言
alphaTao1 小时前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo1 小时前
leetcode 2943
数据结构·算法·leetcode
程序员-King.3 小时前
day134—快慢指针—环形链表(LeetCode-141)
算法·leetcode·链表·快慢指针
Swift社区3 小时前
LeetCode 376 摆动序列
算法·leetcode·职场和发展
黎雁·泠崖3 小时前
整数的N进制字符串表示【递归+循环双版满分实现】
c语言·开发语言
小美单片机4 小时前
Proteus 报错 Unable to open HEX file ‘..\1、程序\jio\jtd.hex‘. [U1]
c语言·单片机·嵌入式硬件·51单片机·proteus
Morwit5 小时前
*【力扣hot100】 448. 找到所有数组中消失的数字
数据结构·算法·leetcode
济6175 小时前
c语言基础(1)--数据类型说明
c语言·开发语言