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;
}
相关推荐
YGGP41 分钟前
【Golang】LeetCode 287. 寻找重复数
开发语言·leetcode·golang
前端小白在前进41 分钟前
力扣刷题:千位分割数
javascript·算法·leetcode
黎雁·泠崖44 分钟前
指针家族高阶篇:字符指针、数组指针、函数指针及转移表应用
c语言·开发语言
小年糕是糕手1 小时前
【C/C++刷题集】string类(一)
开发语言·数据结构·c++·算法·leetcode
努力学算法的蒟蒻1 小时前
day40(12.21)——leetcode面试经典150
算法·leetcode·面试
yuniko-n1 小时前
【力扣 SQL 50】子查询篇
数据库·sql·leetcode
月明长歌1 小时前
Java数据结构:PriorityQueue堆与优先级队列:从概念到手写大根堆
java·数据结构·python·leetcode·
未来之窗软件服务1 小时前
幽冥大陆(五十七)ASR whisper-cli命令行使用 C语言—东方仙盟筑基期
c语言·开发语言·whisper·仙盟创梦ide·东方仙盟·东方仙盟自动化·东方仙盟商业开发
月明长歌1 小时前
【码道初阶】LeetCode面试题 17.14 最小 K 个数:两种堆解法的“同题不同命”
算法·leetcode·职场和发展
程芯带你刷C语言简单算法题1 小时前
Day33~实现一个算法来识别一个字符串。
c语言·算法·c