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;
}
相关推荐
你怎么知道我是队长5 小时前
C语言---头文件
c语言·开发语言
3有青年6 小时前
nios ii 中 ‘ALT_CPU_FREQ‘ could not be resolved的分析和解决办法
c语言·fpga开发
June`6 小时前
全排列与子集算法精解
算法·leetcode·深度优先
夏鹏今天学习了吗7 小时前
【LeetCode热题100(78/100)】爬楼梯
算法·leetcode·职场和发展
圣保罗的大教堂7 小时前
leetcode 712. 两个字符串的最小ASCII删除和 中等
leetcode
ALzc9 小时前
深度剖析EtherCAT FOE功能:ARM固件升级的数据传输与状态机实现
c语言·stm32·ethercat·foe
宵时待雨10 小时前
数据结构(初阶)笔记归纳3:顺序表的应用
c语言·开发语言·数据结构·笔记·算法
智者知已应修善业10 小时前
【C语言 dfs算法 十四届蓝桥杯 D飞机降落问题】2024-4-12
c语言·c++·经验分享·笔记·算法·蓝桥杯·深度优先
有一个好名字10 小时前
力扣-确定两个字符串是否接近
算法·leetcode·职场和发展
无限进步_11 小时前
【C语言&数据结构】二叉树遍历:从前序构建到中序输出
c语言·开发语言·数据结构·c++·算法·github·visual studio