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;
}
相关推荐
Wils0nEdwards28 分钟前
Leetcode 缺失的第一个正整数
leetcode
爱编程的小新☆3 小时前
C语言内存函数
c语言·开发语言·学习
snowful world4 小时前
vs2022链表的创建和打印(c语言版)
c语言·数据结构·链表
__AtYou__5 小时前
Golang | Leetcode Golang题解之第405题数字转换为十六进制数
leetcode·golang·题解
小周的C语言学习笔记5 小时前
鹏哥C语言33---循环语句 for
c语言·c++·算法
LaoWaiHang6 小时前
C语言从头学60——学习头文件math.h(三)
c语言
程序猿练习生6 小时前
C++速通LeetCode简单第16题-买卖股票的最佳时机
开发语言·c++·leetcode
Chase-Hart6 小时前
【每日一题】LeetCode 1184.公交站间的距离问题(数组)
java·算法·leetcode·eclipse·intellij-idea
只对您心动6 小时前
【QT】实现TCP服务器,客户端之间的通信
linux·服务器·c语言·开发语言·c++·qt·tcp/ip
Chase-Hart8 小时前
【每日一题】LeetCode 815.公交路线(广度优先搜索、数组、哈希表)
数据结构·算法·leetcode·散列表·宽度优先