C语言 | Leetcode C语言题解之第385题迷你语法分析器

题目:

C语言 | Leetcode C语言题解之第385题迷你语法分析器_第1张图片

题解:

#define MAX_NEST_LEVEL 50001

struct NestedInteger* deserialize(char * s){
    if (s[0] != '[') {
        struct NestedInteger * ni = NestedIntegerInit();
        NestedIntegerSetInteger(ni, atoi(s));
        return ni;
    }
    struct NestedInteger **stack = (struct NestedInteger **)malloc(sizeof(struct NestedInteger *) * MAX_NEST_LEVEL);
    int top = 0;
    int num = 0;
    bool negative = false;
    int n = strlen(s);
    for (int i = 0; i < n; i++) {
        char c = s[i];
        if (c == '-') {
            negative = true;
        } else if (isdigit(c)) {
            num = num * 10 + c - '0';
        } else if (c == '[') {
            struct NestedInteger * ni = NestedIntegerInit();
            stack[top++] = ni;
        } else if (c == ',' || c == ']') {
            if (isdigit(s[i - 1])) {
                if (negative) {
                    num *= -1;
                }
                struct NestedInteger * ni = NestedIntegerInit();
                NestedIntegerSetInteger(ni, num);
                NestedIntegerAdd(stack[top - 1], ni);
            }
            num = 0;
            negative = false;
            if (c == ']' && top > 1) {
                struct NestedInteger *ni = stack[top - 1];
                top--;
                NestedIntegerAdd(stack[top - 1], ni);
            }
        }
    }
    struct NestedInteger * res = stack[top - 1];
    free(stack);
    return res;
}

你可能感兴趣的:(分享,C语言,Leetcode,题解)