You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.6 KiB

#include <bits/stdc++.h>
using namespace std;
// 测试用例:
// (23+124)*(98-2)
// 中缀转后缀
unordered_map<char, int> g{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; // 操作符优化级
string infixToPostfix(string s) {
stack<char> stk; // 栈
string t; // 结果串
for (int i = 0; i < s.size(); i++) {
// ①数字
if (isdigit(s[i])) {
int x = 0;
while (i < s.size() && isdigit(s[i])) {
x = x * 10 + s[i] - '0';
i++;
}
i--;
t += to_string(x) + " ";
} else if (isalpha(s[i])) // ②字符,比如a,b,c
t.push_back(s[i]), t.push_back(' ');
else if (s[i] == '(') // ③左括号
stk.push(s[i]); // 左括号入栈
else if (s[i] == ')') { // ④右括号
while (stk.top() != '(') { // 让栈中元素(也就是+-*/和左括号)一直出栈,直到匹配的左括号出栈
t.push_back(stk.top()), t.push_back(' ');
stk.pop();
}
stk.pop(); // 左括号也需要出栈
} else {
// ⑤操作符 +-*/
while (stk.size() && g[s[i]] <= g[stk.top()]) {
t.push_back(stk.top()), t.push_back(' ');
stk.pop();
}
stk.push(s[i]); // 将自己入栈
}
}
// 当栈不为空时,全部输出
while (stk.size()) {
t.push_back(stk.top()), t.push_back(' ');
stk.pop();
}
return t;
}
// 判断字符是否是操作符
bool isOp(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 后缀表达式求值
int eval(string s) {
stack<int> stk; // 后缀表达式求值要使用到一个栈
// 构造一个字符串流,方便处理带空格的后缀表达式
stringstream s1(s);
string c;
while (s1 >> c) {
if (isOp(c[0])) { // 如果是操作数,将其转换为整数并入栈
int a = stk.top();
stk.pop();
int b = stk.top();
stk.pop();
if (c == "+") stk.push(b + a);
if (c == "-") stk.push(b - a);
if (c == "*") stk.push(b * a);
if (c == "/") stk.push(b / a);
} else
stk.push(stoi(c));
}
return stk.top();
}
int main() {
string s;
cin >> s;
// 中缀转后缀
s = infixToPostfix(s);
// 后缀表达式求值
cout << eval(s) << endl;
return 0;
}