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;
}
相关推荐
Trouvaille ~1 分钟前
【动态规划篇】专题(一):斐波那契模型——从数学递推到算法思维
c++·算法·leetcode·青少年编程·面试·动态规划·入门
样例过了就是过了22 分钟前
LeetCode热题100 回文链表
数据结构·算法·leetcode·链表
小刘爱玩单片机1 小时前
【stm32协议外设篇】- HX1838 红外接收头
c语言·stm32·单片机·嵌入式硬件
小刘爱玩单片机1 小时前
【stm32协议外设篇】- DS18B20 单总线数字温度检测模块
c语言·stm32·单片机·嵌入式硬件
We་ct2 小时前
LeetCode 637. 二叉树的层平均值:BFS层序遍历实战解析
前端·数据结构·算法·leetcode·typescript·宽度优先
I_LPL2 小时前
day36 代码随想录算法训练营 动态规划专题4
java·算法·leetcode·动态规划·hot100
We་ct2 小时前
LeetCode 199. 二叉树的右视图:层序遍历解题详解
前端·算法·leetcode·typescript·广度优先
bepeater12343 小时前
Laravel9.X核心特性全面解析
c语言·c++·c#·php
逆境不可逃3 小时前
LeetCode 热题 100 之 48.旋转图像
算法·leetcode·职场和发展
Frostnova丶3 小时前
LeetCode 1022. 从根到叶的二进制数之和
算法·leetcode