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;
}
相关推荐
Swift社区35 分钟前
涂色不踩雷:如何优雅解决 LeetCode 栅栏涂色问题
算法·leetcode·职场和发展
冠位观测者38 分钟前
【Leetcode 每日一题】2900. 最长相邻不相等子序列 I
数据结构·算法·leetcode
努力写代码的熊大39 分钟前
链表的中间结点数据结构oj题(力扣876)
数据结构·leetcode·链表
越城1 小时前
深入理解二叉树:遍历、存储与算法实现
c语言·数据结构·算法
努力的小帅2 小时前
C++_STL_map与set
开发语言·数据结构·c++·学习·leetcode·刷题
双叶8363 小时前
(C语言)超市管理系统 (正式版)(指针)(数据结构)(清屏操作)(文件读写)
c语言·开发语言·数据结构·c++·windows
序属秋秋秋3 小时前
《数据结构初阶》【二叉树 精选9道OJ练习】
c语言·数据结构·c++·算法·leetcode
Tiny番茄3 小时前
LeetCode 235. 二叉搜索树的最近公共祖先 LeetCode 701.二叉搜索树中的插入操作 LeetCode 450.删除二叉搜索树中的节点
数据结构·算法·leetcode
欧先生^_^4 小时前
rust语言,与c,go语言一样也是编译成二进制文件吗?
c语言·golang·rust
再睡一夏就好5 小时前
从硬件角度理解“Linux下一切皆文件“,详解用户级缓冲区
linux·服务器·c语言·开发语言·学习笔记