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;
}
相关推荐
沉默-_-1 分钟前
力扣hot100普通数组(1)--C++
java·数据结构·算法·leetcode·数组
Once_day3 分钟前
C++之《Effective C++》读书总结(1)
c语言·c++·effective c++
爱吃生蚝的于勒6 分钟前
【Linux】进程信号的保存(二)
linux·运维·服务器·c语言·数据结构·c++·算法
小程同学>o<9 分钟前
嵌入式之C/C++(一)关键字
c语言·开发语言·c++·嵌入式软件面试
im_AMBER20 分钟前
Leetcode 108 交换链表中的节点
数据结构·笔记·学习·算法·leetcode·链表
TracyCoder12328 分钟前
LeetCode Hot100(14/100)——73. 矩阵置零
算法·leetcode·矩阵
FMRbpm34 分钟前
邻接矩阵练习1--------LCP 07.传递信息
数据结构·c++·算法·leetcode·深度优先·新手入门
老鼠只爱大米40 分钟前
LeetCode经典算法面试题 #146:LRU 缓存(双向链表、线程安全等多种实现方案详细解析)
算法·leetcode·lru·lru缓存·双向链表
郝学胜-神的一滴2 小时前
Linux Socket编程核心:深入解析sockaddr数据结构族
linux·服务器·c语言·网络·数据结构·c++·架构
云深麋鹿3 小时前
五.排序笔记
c语言·数据结构·算法·排序算法