Leetcode 224. 基本计算器 (处理加减括号的四则运算,parse和栈的思想)

 

注意这样一个测试用例

这种题目,在面试中,我们推荐使用双栈的写法,定义一个符号栈和数字栈,如果遇到数字,那么解析完整个数字,将数字放到数字栈里,如果遇到运算符,将运算符放到符号栈里。如果遇到左括号,将左括号入栈,如果遇到右括号,对数字栈里的数字做运算,一直算道左括号为止。最后要将栈里面的数算完。

这里用到一些优化的思想,每次遇到符号时,先把栈里面能算完的算完。

这里要注意一种特殊情况,就是第一个数是负数的情况,我们这里用到一个技巧,如果发现第一个位是负数,先把数字栈里面压入一个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();
    }
};

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值