Simple C++ solution


  • 0
    B
    class Solution {
    public:
        void skipSpace(const string& s, int& i) {
            while (i < (int)s.length() && s[i] == ' ')
                i++;
        }
    
        int expr(const string& s, int& i) {
            int value = 0;
            int op = '+';
    
            skipSpace(s, i);
            while (i < (int)s.length() && s[i] != ')') {
                if (s[i] == '+' || s[i] == '-') {
                    op = s[i++];
                } else {
                    int x = 0;
                    if (s[i] == '(') {
                        i++; // '('
                        x = expr(s, i);
                        i++; // ')'
                    } else {
                        while (i < (int)s.length() && isdigit(s[i]))
                            x = x * 10 + s[i++] - '0';
                    }
        
                    if (op == '+')
                        value += x;
                    else
                        value -= x;
                }
                skipSpace(s, i);
            }
            return value;
        }
        
        int calculate(string s) {
            int i = 0;
            return expr(s, i);
        }
    };
    

Log in to reply
 

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