20-line recursive solution


  • 0
    L
    class Solution {
        int getNum(const string &s, int &pos) {
            int num = 0;
            if (s[pos] == '(') num = calculate(s, ++pos), pos += 1;
            else while (pos != s.size() && isdigit(s[pos])) num = num * 10 + s[pos++] - '0';
            return num;
        }
    
        
        int calculate(const string &s, int &pos) {
            int num = getNum(s, pos);
            while (pos < s.size() && s[pos] != ')') num += (s[pos++] == '+'? getNum(s, pos): - getNum(s, pos));
            return num;
        }
        
    public:
        int calculate(const string &s) {
            string tmp; int idx = 0;
            for (int i = 0; i < s.size(); i++) if (s[i] != ' ') tmp.push_back(s[i]);
            return calculate(tmp, idx);
        }
    };
    

Log in to reply
 

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