注意这样一个测试用例
这种题目,在面试中,我们推荐使用双栈的写法,定义一个符号栈和数字栈,如果遇到数字,那么解析完整个数字,将数字放到数字栈里,如果遇到运算符,将运算符放到符号栈里。如果遇到左括号,将左括号入栈,如果遇到右括号,对数字栈里的数字做运算,一直算道左括号为止。最后要将栈里面的数算完。
这里用到一些优化的思想,每次遇到符号时,先把栈里面能算完的算完。
这里要注意一种特殊情况,就是第一个数是负数的情况,我们这里用到一个技巧,如果发现第一个位是负数,先把数字栈里面压入一个0,即可。
class Solution {
public:
void eval(stack<int>& nums, stack<char> &op){
int b = nums.top();nums.pop();
int a = nums.top();nums.pop();
char c = op.top();op.pop();
int r;
if(c=='+') r = a+b;
else r = a-b;
nums.push(r);
}
int calculate(string s) {
stack<int> nums;
stack<char> op;
int n = s.size();
int i = 0;
while(i<n&&s[i]==' ') i++;
if(s[i]=='-') nums.push(0);
for(;i<n;i++){
char c = s[i];
if(c==' ') continue;
if(isdigit(c)){
int x = 0 , j = i;
while(j<n&&isdigit(s[j])){
x = x*10 + (s[j++]-'0');
}
nums.push(x);
i = j-1;
}else if(c=='('){
op.push(c);
}else if(c==')'){
while(op.top()!='(') eval(nums,op);
op.pop();
}else{
while(op.size() && op.top() != '(') eval(nums, op);
op.push(c);
}
}
while(!op.empty()) eval(nums,op);
return nums.top();
}
};