【栈】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;
}

浙公网安备 33010602011771号