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;
}
相关推荐
dying_man1 小时前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel1 小时前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
草莓熊Lotso2 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM2 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法
GGBondlctrl2 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想
CodeOfCC3 小时前
c语言 封装跨平台线程头文件
linux·c语言·windows
momo卡3 小时前
MinGW-w64的安装详细步骤(c_c++的编译器gcc、g++的windows版,win10、win11真实可用)
c语言·c++·windows
超的小宝贝4 小时前
数据结构算法(C语言)
c语言·数据结构·算法
凤年徐6 小时前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表