Simple C++ solution; no corner cases


  • 0
    V
    class Solution {
    public:
        int calculate(string s) {
            return simpleCalc(s, 0, s.size());   
        }
            
        int simpleCalc(string& s, int start, int end){ 
            
            int sum = 0;
            stack<char> op;
            stack<int> sums;
            op.push('+');
            for(int i = start; i < end; i++){
            
                if(s[i]==')'){
                    sum = (op.top()=='+' ? sum + sums.top() : -sum + sums.top());
                    op.pop();
                    sums.pop();
                    continue;
                }
                
                if(s[i]=='('){
                    sums.push(sum);
                    op.push('+');
                    sum = 0;
                    continue;
                }
                
                if(s[i]==' '){
                    continue;
                }
                
                if(s[i] == '+'){ op.push('+'); continue; }
                if(s[i] == '-'){ op.push('-'); continue; }
                
                int num=0;
                while(i<s.size() && isdigit(s[i])){
                        num = num*10 + s[i]-'0';
                        i++;
                }
                i--;
                sum += (op.top()=='+') ? num: -num;
                op.pop();
            }
            
            return sum;
        }
        
    };

Log in to reply
 

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