多学习。

【栈】AcWing3302. 表达式求值

ACWing3302.表达式求值

题解


#include <iostream>
#include <stack>
#include <unordered_map>
#include <cstring>

using namespace std;

unordered_map<char, int> pr{ {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2} };
stack<int> nums;
stack<int> op;

void eval()
{
    int a = nums.top(); nums.pop();
    int b = nums.top(); nums.pop();
    char c = op.top(); op.pop();
    if(c == '+') nums.push(b + a);
    else if(c == '-') nums.push(b - a);
    else if(c == '*') nums.push(b * a);
    else nums.push(b / a);
}

int main()
{
    string s;
    cin >> s;
    for(int i = 0; i < s.size(); ++i)
    {
        auto c = s[i];
        if(isdigit(c))
        {
            int num = 0, j = i;
            while(j < s.size() && isdigit(s[j]) )
                num = num * 10 + (s[j ++ ] - '0');
            i = j - 1;
            nums.push(num);
        }
        else if(c == '(') op.push(c);
        else if(c == ')')
        {
            while(op.top() != '(') eval();  //从左往右的计算已经完成,类似于完成一个式子,进行从右往左的计算
            op.pop(); //删除左括号
        }
        else  //遇到新的四则符号是否进行一次从左往右计算
        {
            //以树的形式理解:遍历完子树
            //要把前面的计算问题处理掉不然会出错(清空子树)比如说:(14/2*7+2)若使用if会导致 2/14+2在for循坏外的while中先计算14+2
            while(op.size() && op.top() != '('  && pr[c] <= pr[op.top()])
                eval();
            op.push(c);
        }
    }
    while(op.size()) eval();
    cout << nums.top() << endl;
    return 0;
}

posted @   czyaaa  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示