Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval
built-in library function.
class Solution {
public:
/*algorithm: stack soluton
two stack: operand stack, and operator stack
transform it to reverse polish notation,then compute
but we can skip this step
one pass
*/
void tryExecute(stack<int>&opStk,stack<int>&numStk){
if(numStk.size() < 2 || opStk.empty())return;
int op = opStk.top();
if(op =='+' || op == '-'){
int r = numStk.top();numStk.pop();
int l = numStk.top();numStk.pop();
numStk.push(op == '+'?(l+r):(l-r));
opStk.pop();
}
}
int numLength(string &s,int start){
int i = start;
for(;i < s.size() && isdigit(s[i]);i++);
return i - start;
}
int calculate(string s) {
stack<int>opStk,numStk;
int next;
for(int i = 0;i < s.size();){
char c = s[i];
next = i + 1;
if(c == '(')opStk.push(c);
else if(c == ')'){
opStk.pop();
tryExecute(opStk,numStk);
} else if(c == '+' || c == '-') opStk.push(c);
else if(isdigit(c)){
int len = numLength(s,i);
numStk.push(stoi(s.substr(i,len)));
tryExecute(opStk,numStk);
next = i + len;
}
//update i pos
i = next;
}
return numStk.top();
}
};