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;
}
相关推荐
恒森宇电子有限公司1 小时前
IP5326_BZ 支持C同口输入输出的移动电源芯片 2.4A的充放电电流 支持4LED指示灯
c语言·开发语言·单片机
曙曙学编程2 小时前
stm32——NVIC,EXIT
c语言·c++·stm32·单片机·嵌入式硬件
HUST2 小时前
C语言 第三讲:分支和循环(上)
c语言·开发语言
今日待办2 小时前
Arduino Nano33 BLESense Rev2【室内空气质量检测语音识别蓝牙调光台灯】
c语言·单片机·嵌入式硬件·mcu·语音识别·ardunio·arduinonano33
这里没有酒5 小时前
[C语言] 结构体 内存对齐规则 内存大小计算
c语言·开发语言
Miraitowa_cheems6 小时前
LeetCode算法日记 - Day 34: 二进制求和、字符串相乘
java·算法·leetcode·链表·职场和发展
半夜吃早餐7 小时前
【STM32HAL-----NRF24L01】
c语言·开发语言·stm32·单片机·嵌入式硬件
程序员Xu9 小时前
【LeetCode热题100道笔记】二叉树的直径
笔记·算法·leetcode
ShineWinsu9 小时前
对于单链表相关经典算法题:206. 反转链表及876. 链表的中间结点的解析
java·c语言·数据结构·学习·算法·链表·力扣