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;
}
相关推荐
01二进制代码漫游日记2 小时前
C/C++中的内存区域划分
c语言·jvm·数据结构·学习
炸膛坦客2 小时前
单片机/C语言八股:(三)C 语言编译器的优化功能,包括 keil(仅作了解)
c语言·单片机·嵌入式硬件
人道领域2 小时前
【绝对干货】C语言常量,变量,内存全方位总结:从入门到精通,这一篇就够了!
c语言·开发语言
代码改善世界2 小时前
【数据结构】八大排序算法详解(C语言实现)|插入排序、希尔排序、选择排序、堆排序、冒泡排序、快速排序、归并排序、计数排序
c语言·数据结构·排序算法
luckycoding3 小时前
3005. 最大频率元素计数
算法·leetcode·职场和发展
香水5只用六神3 小时前
【TIM】基本定时器定时实验(2)
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·学习
TrueDei3 小时前
linux-C/C++主子进程同时占用主进程文件描述符问题
linux·c语言·c++
小龙报3 小时前
【数据结构与算法】环与相遇:链表带环问题的底层逻辑与工程实现
c语言·数据结构·c++·物联网·算法·链表·visualstudio
一叶落4384 小时前
LeetCode 67. 二进制求和(C语言详解 | 双指针模拟加法)
c语言·数据结构·算法·leetcode