6ms C solution


  • 0
    V

    The idea is to expand the expression by evaluating all numbers and add them up later. Numbers are evaluated as positive or negative depending on a "sign" which negates when minus operator is encountered. For example, 1 - (2 - (3 - 4)), numbers added to the list are: 1, -2, 3, -4.

    char* clean(char* s);
    char* calculateSub(char* s, int sign);
    char* addNumber(char* s, int sign);
    char* getNumber(char* s, int* num);
    
    int nums[100000]; // To deal with very long tests
    int count = 0;
    
    int calculate(char* s)
    {
        int res = 0;
    
        // Eliminate spaces
        s = clean(s);
    
        s = calculateSub(s, 1);
    
        // Add numbers up
        while (count > 0)
            res += nums[--count];
    
        return res;
    }
    
    char* calculateSub(char* s, int sign)
    {
        if (*s == '(')
            s = calculateSub(++s, sign);
    
        while (*s != '\0' && *s != ')') {
            if (*s == '+') {
                s++;
                if (*s == '(')
                    s = calculateSub(++s, sign);
                else
                    s = addNumber(s, sign);
            } else if (*s == '-') {
                s++;
                if (*s == '(')
                    s = calculateSub(++s, -sign);
                else
                    s = addNumber(s, -sign);
            } else
                s = addNumber(s, sign);
        }
    
        if (*s == ')')
            s++;
    
        return s;
    }
    
    char* clean(char* s)
    {
        char* new = malloc(sizeof(char) * (strlen(s) + 1));
        char* cur = new;
    
        for (; *s != '\0'; s++)
            if (*s != ' ')
                *(cur++) = *s;
        *cur = '\0';
    
        return new;
    }
    
    char* addNumber(char* s, int sign)
    {
        int num;
    
        s = getNumber(s, &num);
        nums[count++] = num * sign;
    
        return s;
    }
    
    char* getNumber(char* s, int* num)
    {
        if (*s == '\0')
            return s;
    
        *num = 0;
    
        while (*s >= '0' && *s <= '9') {
            *num = *num * 10 + (*s - '0');
            s++;
        }
    
        return s;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.