以牛客华为机试题为例 HJ50 四则运算
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
bool is_digit(char c) {
return c >= '0' && c <= '9';
}
void eval() {
auto b = num.top();
num.pop();
auto a = num.top();
num.pop();
auto c = op.top();
op.pop();
int x;
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
//字符串预处理
string preprocess(string& s) {
string res;
for (int i = 0; i < s.size(); i ++) {
if (s[i] == ' ') continue;
else if (s[i] == '[' || s[i] == '(' || s[i] == '{') res += '(';
else if (s[i] == ']' || s[i] == ')' || s[i] == '}') res += ')';
else res += s[i];
if (res.back() == '(') {
//先把空格过滤在判断(是不是挨着正负号了
int j = i + 1;
while (j < s.size() && s[j] == ' ') j ++;
if (!is_digit(s[j])) res += '0';
i = j - 1;
}
}
return res;
}
int main() {
string s;
// cin >> s;//注意cin读入字符串遇到空格或者换行就停止了,所以如果题中给的串包含空格就不能用cin读入
getline(cin, s);//如果有空格这样读
s = preprocess(s);
int n = s.size();
num.push(0);
for (int i = 0; i < n; i ++) {
if (is_digit(s[i])) {
int j = i, x = 0;
while (j < n && is_digit(s[j]))
x = x * 10 + s[j ++] - '0';
num.push(x);
i = j - 1;
} else if (s[i] == '(') op.push(s[i]);
else if (s[i] == ')') {
while (op.top() != '(') eval();
op.pop();
} else {
while (op.size() && op.top() != '(' && pr[s[i]] <= pr[op.top()]) eval();
op.push(s[i]);
}
}
while (op.size()) eval();
cout << num.top() << endl;
return 0;
}