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;
}
相关推荐
potato_may30 分钟前
第18讲:C语言内存函数
c语言·数据结构·算法
顾晨阳——1 小时前
C/C++字符串
c语言·c++·字符串
仰泳的熊猫1 小时前
LeetCode:95. 不同的二叉搜索树 II
数据结构·c++·算法·leetcode
Nix Lockhart1 小时前
《算法与数据结构》第七章[算法4]:最短路径
c语言·数据结构·学习·算法·图论
前进之路92 小时前
Leetcode每日一练--28
leetcode
海琴烟Sunshine4 小时前
leetcode 168. Excel 表列名称 python
python·算法·leetcode
1白天的黑夜15 小时前
递归-21.合并两个有序链表-力扣(LeetCode)
c++·leetcode·链表·递归
坚持编程的菜鸟5 小时前
LeetCode每日一题——在区间范围内统计奇数数目
c语言·算法·leetcode
qiuiuiu4135 小时前
正点原子RK3568学习日志6-驱动模块传参
linux·c语言·开发语言·单片机·学习
盛小夏6 小时前
从零开始学C语言:小白也能轻松上手
c语言