【栈】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;
}
分类:
数据结构【算法题】
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具