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;
}
相关推荐
2501_901147831 小时前
学习笔记|LeetCode 739 每日温度:从暴力枚举到单调栈线性最优解
笔记·学习·leetcode
追随者永远是胜利者2 小时前
(LeetCode-Hot100)22. 括号生成
java·算法·leetcode·职场和发展·go
爱编码的小八嘎2 小时前
第2章 认识CPU-2.4 【实例】:在DOS实模式下读取4GB内存(1)
c语言
Electron-er2 小时前
深入解析C语言memcmp函数:内存比较的利器与陷阱(附实战案例)
c语言·开发语言
m0_531237172 小时前
C语言-操作符
c语言·开发语言
追随者永远是胜利者2 小时前
(LeetCode-Hot100)32. 最长有效括号
java·算法·leetcode·职场和发展·go
追随者永远是胜利者2 小时前
(LeetCode-Hot100)31. 下一个排列
java·算法·leetcode·职场和发展·go
m0_531237173 小时前
C语言-指针,结构体
c语言·数据结构·算法
丰海洋3 小时前
leetcode-hot100-1.两数之和
数据结构·算法·leetcode
Frostnova丶3 小时前
LeetCode 401. 二进制手表
算法·leetcode