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;
}
相关推荐
揽星河..22 分钟前
【C语言】函数
c语言·算法
驭渊的小故事1 小时前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
文丑颜不良啊2 小时前
LeetCode1501~1520题目解析
java·leetcode
Navigator_Z3 小时前
LeetCode //C - 1311. Get Watched Videos by Your Friends
c语言·算法·leetcode
Pniubi4 小时前
力扣42接雨水(动态规划法)
算法·leetcode·职场和发展
可乐_不渴4 小时前
# C语言文件操作全解析:从 fopen 到 fclose,一文吃透文件 IO
linux·服务器·c语言
Pniubi4 小时前
力扣46全排列(回溯(递归))
算法·leetcode·职场和发展
文丑颜不良啊5 小时前
LeetCode1461~1480题目解析
java·leetcode
Pniubi15 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
Zwawa18 小时前
串口为什么会丢字节:从轮询到中断和环形缓冲区
c语言·单片机·嵌入式