题解 | #四则运算#

四则运算

https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

#include <iostream>
#include <stack>
#include <unordered_map>
#include <utility>
using namespace std;

void cal(stack<char>& ops, stack<int>& nums) {
    if(ops.empty() || nums.size() < 2) return ;
    char c = ops.top();
    ops.pop();
    int b = nums.top();
    nums.pop();
    int a = nums.top();
    nums.pop();
    if(c == '+') {
        nums.push(a + b);
    } else if(c == '-') {
        nums.push(a - b);
    } else if(c == '*') {
        nums.push(a * b);
    } else if(c == '/') {
        nums.push(a / b);
    }
}
void setPri(unordered_map<char, int>& mp) {
    mp['+'] = 1;
    mp['-'] = 1;
    mp['*'] = 2;
    mp['/'] = 2;
}
int main() {
    string s;
    cin >> s;
    for(char& i : s)
        if(i == '[' || i == '{') i = '(';
        else if(i == ']' || i == '}') i = ')';
    stack<int> nums;
    stack<char> ops;
    unordered_map<char, int> mp;
    setPri(mp);


    nums.push(0);
    for(int i = 0; i < s.length(); i++) {
        if(s[i] == ' ') continue;
        if(s[i] == '(') {
            ops.push('(');
            continue;
        }
        if(s[i] == ')') {
            while(ops.top() != '(') {
                cal(ops, nums);
            }
            ops.pop();
            continue;
        }
        if(i > 0 && s[i - 1] == '(' && (s[i] == '+' || s[i] == '-')) {
            nums.push(0);
            ops.push(s[i]);
            continue;
        }
        if(s[i] <= '9' && s[i] >= '0') {
            int t = 0;
            while(isdigit(s[i])) {
                t = t * 10 + s[i] - '0';
                i++;
            }
            nums.push(t);
            i--;
            continue;
        }
        while(!ops.empty() && ops.top() != '(') {
            if(mp.find(ops.top())->second >= mp.find(s[i]) ->second)
                cal(ops, nums);
            else break;
        } 
        ops.push(s[i]);
    }
    while(!ops.empty() && ops.top() != '(') cal(ops, nums);
    cout << nums.top() << endl;
    return 0;
}

直接套三叶女神统计好的模板。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务