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:
int calculate(string s) {
int n = s.size();
if (n < 1)
{
return 0;
}
s = '(' + s + ')';
n += 2;
int result = 0;
stack<char> symbol;
stack<int> num;
int value = 0;
bool numFound = false;
for (int i = 0; i < n; i++)
{
if (s[i] <= '9' && s[i] >= '0')
{
numFound = true;
value = value*10 + s[i] - '0';
continue;
}
else if (numFound)
{
num.push(value);
value = 0;
numFound = false;
}
if (s[i] == ')')
{
int temp = 0;
while (true)
{
int v = num.top();
num.pop();
char w = symbol.top();
symbol.pop();
if (w == '+')
{
temp += v;
}
else if (w == '-')
{
temp -= v;
}
else
{
temp += v;
num.push(temp);
break;
}
}
if (i == n-1)
{
result = temp;
break;
}
}
else if (s[i] == '+' || s[i] == '-' || s[i] == '(')
{
symbol.push(s[i]);
}
}
return result;
}
};