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
题目很容易懂,就是实现个计算功能,肯定是用栈,刚开始没仔细思考,凭感觉写了,结果各种用例错误,囧,比如空格,多位整数可以先存在string中,然后转int,还有就是因为是从左到右结合的倒着入栈比较好,比如2-1+3,如果先把2入栈,那直接倒着出来的时候就是3+1-2,肯定是错的,就得加入很多判断,但是倒着入栈顺序就是一致的,先计算2-1,再+3.这里用了两个栈,一个存符号,一个存数字,计算+-的时候从数字数组中pop两个,运算完再push回去。
class Solution {
public:
//一定要倒着插,如果正着插比如2-1+2则不好运算。
int calculate(string s) {
int newnum = 0;
int res=0;
stack<int>num;//存数字的
stack<char>S;//存运算符
string str;
s = s + ')'; //碰见'('才计算,所以需要在最外面加'()'
s = '(' + s;
for (int i = s.size()-1; i >=0; i--)//倒着入栈
{
if (s[i] == '-' || s[i] == '+')
{
S.push(s[i]);
if (str.size() != 0)
{
res = atoi(str.c_str());//str转int
num.push(res);
str.clear();
}
}
else if (s[i] == '(')//碰见(进行计算
{
if (str.size()!=0)//(前面还有值的话
{
res = atoi(str.c_str());
num.push(res);
str.clear();
}
while (!S.empty() && S.top() != '(')//碰到(则停止
{
if (S.top() == '+' || S.top() == '-')
{
res = num.top();
num.pop();
newnum = num.top();
num.pop();
(S.top() == '+') ? res = res + newnum : res = res - newnum;
num.push(res);
S.pop();//弹出+ 或-
}
else
{
S.pop();//弹出)
break;
}
}
}
else if (s[i] == ')')
{
S.push(')');
}
else
{
if (s[i] != ' ') str = s[i] + str;//把符号之间的数存在string里
}
}
return num.top();
}
};