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;
}
相关推荐
[J] 一坚7 小时前
嵌入式高手C
c语言·开发语言·stm32·单片机·mcu·51单片机·iot
加农炮手Jinx7 小时前
LeetCode 72. Edit Distance 题解
算法·leetcode·力扣
_深海凉_7 小时前
LeetCode热题100-打家劫舍
算法·leetcode·职场和发展
qeen879 小时前
【数据结构】树的基本概念及存储
c语言·数据结构·c++·学习·
pluviophile_s14 小时前
第18讲:⾃定义类型:结构体
c语言·笔记
菜鸟丁小真14 小时前
LeetCode hot100 -73.矩阵置零
数据结构·leetcode·矩阵·知识点总结
We་ct15 小时前
LeetCode 64. 最小路径和:动态规划入门实战
开发语言·前端·算法·leetcode·typescript·动态规划
꧁细听勿语情꧂16 小时前
向下调整算法,top - k 问题,链式结构二叉树,前中后序遍历
c语言·开发语言·数据结构·算法
踩坑记录16 小时前
leetcode hot100 169. 多数元素 easy 技巧 摩尔投票
leetcode
水蓝烟雨16 小时前
3487. 删除后的最大子数组元素和
算法·leetcode·链表