Share my c++ solution , 44ms


  • 0
    Z
    class Solution {
    public:
        int calculate(string s) {
            stack<int> num;
    		stack<char> op;
    		int n = 0;
    		int sum = 0;
    		s = s + "+";
    		int len = s.length();
    		bool rp = false;
    		for (int i = 0; i<len; i++) {
    			if (s[i] >= '0' && s[i] <= '9') {
    				n = n * 10 + s[i] - '0';
    			}
    			else if (s[i] == '(') {
    				op.push(s[i]);
    			}
    			else if (s[i] == ')') {
    				if (!rp) num.push(n);
    				char o = op.top();
    				while (o != '(') {
    					int n1 = num.top();
    					num.pop();
    					int n2 = num.top();
    					num.pop();
    					if (o == '+') num.push(n1 + n2);
    					if (o == '-') num.push(n2 - n1);
    					op.pop();
    					o = op.top();
    				}
    				op.pop();
    				n = 0;
    				rp = true;
    			}
    			else if (s[i] == '+') {
    				if(!rp) num.push(n);
    				else rp = false;
    				if (op.empty() || op.top() == '(') {
    					op.push(s[i]);
    				}
    				else {
    					char o = op.top();
    					int n1 = num.top();
    					num.pop();
    					int n2 = num.top();
    					num.pop();
    					if (o == '+') num.push(n1 + n2);
    					if (o == '-') num.push(n2 - n1);
    					op.pop();
    					op.push(s[i]);
    				}
    				n = 0;
    			}
    			else if (s[i] == '-') {
    				if (!rp) num.push(n);
    				else rp = false;
    				if (op.empty() || op.top() == '(') {
    					op.push(s[i]);
    				}
    				else {
    					char o = op.top();
    					int n1 = num.top();
    					num.pop();
    					int n2 = num.top();
    					num.pop();
    					if (o == '+') num.push(n1 + n2);
    					if (o == '-') num.push(n2 - n1);
    					op.pop();
    					op.push(s[i]);
    				}
    				n = 0;
    			}
    		}
    		return num.top();
        }
    };

Log in to reply
 

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