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;
}
相关推荐
一起努力啊~21 分钟前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode
leoufung33 分钟前
LeetCode 221:Maximal Square 动态规划详解
算法·leetcode·动态规划
源代码•宸37 分钟前
Leetcode—39. 组合总和【中等】
经验分享·算法·leetcode·golang·sort·slices
好易学·数据结构38 分钟前
可视化图解算法77:零钱兑换(兑换零钱)
数据结构·算法·leetcode·动态规划·力扣·牛客网
AlenTech1 小时前
226. 翻转二叉树 - 力扣(LeetCode)
算法·leetcode·职场和发展
Tisfy1 小时前
LeetCode 1458.两个子序列的最大点积:动态规划
算法·leetcode·动态规划·题解·dp
求梦8201 小时前
【力扣hot100题】合并区间(9)
算法·leetcode·职场和发展
阿华hhh2 小时前
项目(购物商城)
linux·服务器·c语言·c++
方便面不加香菜2 小时前
基于顺序表实现通讯录项目
c语言·数据结构
爱编程的小吴2 小时前
【力扣练习题】121. 买卖股票的最佳时机
算法·leetcode·职场和发展