基本计算器II

10 篇文章 0 订阅
1 篇文章 0 订阅

227. Basic Calculator II

来源: LeetCode 227. Basic Calculator II

题目描述

227. Basic Calculator II
Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7
Example 2:

Input: " 3/2 "
Output: 1
Example 3:

Input: " 3+5 / 2 "
Output: 5
Note:

You may assume that the given expression is always valid.
Do not use the eval built-in library function.

思路分析

用栈加自定义优先级

代码

class Solution {
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
#define ALL(A) A.begin(),A.end()
using VI = vector<int>;
using VII = vector<VI>;
using VD = vector<double>;
typedef pair<int, int> PI;
public:
    int calculate(string s) {
        // stack + priority
        // * / -> 2 + - -> 0
        // stack_num stack_sign
        stack<int>st1;
        stack<char>st2;
        unordered_map<char, int>mp = {
            {'*', 2},
            {'/', 2},
            {'+', 1},
            {'-', 1},
        }; // priority
        string str;
        st1.push(0);
        for(auto c:s){
            if(c>47 && c<58) str+=c;
            else{
                if(mp.find(c) == mp.end()) continue;
                st1.push(stoi(str)); // 计算得到前面的数字
                while(!st2.empty() && mp[c]<=mp[st2.top()]) {
                    int a = st1.top(); st1.pop();
                    int b = st1.top(); st1.pop();
                    // cout << b << st2.top() << a << '=';
                    st1.push(getval(a, b, st2.top()));
                    st2.pop();
                    // cout << st1.top() << endl;
                } // 判断优先级运算
                st2.push(c);
                str = "";
            }
        }
        if(SIZE(str)) st1.push(stoi(str));
        while(!st2.empty()){
            char c = st2.top(); st2.pop();
            int a = st1.top(); st1.pop();
            int b = st1.top(); st1.pop();
            // cout << b << c << a << '=';
            st1.push(getval(a, b, c));
            // cout << st1.top() << endl;
        }
        return st1.top();
    }
    int getval(int a, int b, char c){
        switch(c){
            case '*': b *= a;break;
            case '/': b /= a;break;
            case '+': b += a;break;
            case '-': b -= a;
        }
        return b;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值