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;
}
相关推荐
普通攻击往后拉9 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
Nebula嵌入式9 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
天空'之城11 小时前
C 语言工业级通用组件手写 23:卡尔曼滤波(简易版)
c语言·卡尔曼滤波·嵌入式算法·工业级组件
888CC++12 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++
库玛西14 小时前
C++ 运行时多态 :核心总结与原理图解
c语言·c++·笔记
橘子汽水16816 小时前
Leetcode 230,98:二叉搜索树中第K小的元素,验证二叉搜索树
算法·leetcode·职场和发展
天空'之城16 小时前
C 语言工业级通用组件手写 21:限幅消抖滤波
c语言·嵌入式算法·工业级组件·限幅消抖滤波
Aurorar0rua16 小时前
CS50 x 2024 Notes Algorithms - 07
c语言·开发语言·学习方法
神罚天下ET16 小时前
典型arm位单片机启动流程(从上电到main.c)
c语言·arm开发·单片机
普通攻击往后拉18 小时前
Leetcode 448. 找到所有数组中消失的数字
算法·leetcode·职场和发展