13ms C++ solution


  • 0
    L
    
    int calculate(string s) {
        stack<int> signStack;
        stack<int> resStack;
        int sign = 1;
        int result = 0;
        int i = 0;
        while (i < s.length())
        {
            switch (s[i])
            {
            case ' ':
                //skip spaces
                break;
            case '+':
                sign = 1;
                break;
            case '-':
                sign = -1;
                break;
            case '(':
                //push current calculated result and latest sign on the stack
                resStack.push(result);
                signStack.push(sign);
                result = 0;
                sign = 1;
                break;
            case ')':
                //pop off from the stack and combine with the result in braces
                result = resStack.top() + signStack.top()*result;
                resStack.pop();
                signStack.pop();
                break;
            default:
                if (isdigit(s[i]))
                {
                    int op1 = s[i] - '0';
                    while (isdigit(s[++i])) 
                        op1 = op1 * 10 + s[i] - '0';
                    result += sign * op1;
                    --i;
                }
                break;
            }
            i++;
        }
    
        return result;
    }
    

Log in to reply
 

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