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用栈来实现,遇到'('就把之前计算的结果和'('之前的符号压入栈中,遇到')'就把当前计算好的结果乘以栈顶的符号并加上栈顶的结果。
class Solution {
public:
int calculate(string s) {
if(s.size()==0) return 0;
stack<int> ss;
int res = 0;
int sign = 1;
for(int i = 0; i < s.size(); i++)
{
char c = s[i];
if(c-'0'>=0 && c-'0'<=9)
{
int num = c-'0';
while(i+1<s.size() && s[i+1]-'0'>= 0 && s[i+1]-'0'<=9)
{
num = 10*num + (s[++i]-'0');
}
res += sign*num;
}
else if(c == '+')
{
sign = 1;
}
else if(c == '-')
{
sign = -1;
}
else if(c == '(')
{
ss.push(res);
res = 0;
ss.push(sign);
sign = 1;
}
else if(c == ')')
{
int s1 = ss.top();
ss.pop();
int s2 = ss.top();
ss.pop();
res = s1*res + s2;
sign = 1;
}
}
return res;
}
};