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;
}
相关推荐
zlinear数据采集卡1 小时前
基准电压电路深度解析:从理论参数到ZLinear采集卡的精准参考实战
c语言·单片机·嵌入式硬件·fpga开发·自动化
风筝在晴天搁浅2 小时前
快手 CodeTop LeetCode 224.基本计算器
数据结构·算法·leetcode
日晨难再2 小时前
C语言&Python&Bash&Tcl:全局变量和局部变量
c语言·python·bash·tcl
8Qi83 小时前
LeetCode 31:下一个排列(Next Permutation)—— 完整题解笔记 ✅
笔记·算法·leetcode·指针·思维·排列
AI科技星3 小时前
基于光速螺旋第一性原理:$G,\varepsilon_0,\alpha$引电统一完整推导+严谨证明+高精度数值全维度分析
c语言·开发语言·网络·量子计算·agi
xgstb4 小时前
C语言随机数生成技巧
c语言·伪随机数·time函数·srand函数·随机数生成
玖釉-4 小时前
编辑距离(Edit Distance)——从字符串相似度到动态规划经典模型
算法·leetcode·动态规划
c238564 小时前
c/c++中的二叉树进阶
c语言·c++·算法
0x3F(小茶)5 小时前
嵌入式C设计模式完全指南(基于《C嵌入式编程设计模式》)
c语言·开发语言·单片机·嵌入式硬件·设计模式
_日拱一卒5 小时前
LeetCode:46全排列
算法·leetcode·职场和发展