表达式匹配的问题,可以利用栈来解决。这里利用两个栈,数字栈和符号栈,实现表达式的匹配。这里需要特别注意的几个点:1. 注意符号优先级情况下的处理问题,在操作符入栈的时候,要进行符号优先级的比较,如果入栈符号的优先级小于或者等于栈顶符号,则先对优先级更高的栈顶符号进行运算; 2. 注意处理负数的问题,如果碰到负数,则可以将0加入数字栈中。
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <unordered_map>
using namespace std;
void cal(stack<int> &nums, stack<char> &symbols) {
int num1 = nums.top();
nums.pop();
int num2 = nums.top();
nums.pop();
char ch = symbols.top();
symbols.pop();
int ans = 0;
switch (ch) {
case '+': { ans = num2 + num1; break; }
case '-': { ans = num2 - num1; break; }
case '*': { ans = num2 * num1; break; }
case '/': { ans = num2 / num1; break; }
}
nums.push(ans);
}
int main() {
string s;
getline(cin, s, '\n');
stack<int> nums;
stack<char> symbols;
unordered_map<char,int> priority;
priority['('] = 0; priority[')'] = 0; priority['+'] = 1; priority['-'] = 1; priority['*'] = 2; priority['/'] = 2;
if (s[0] == '-') nums.push(0); // 不要忘记考虑第一个数字为负数的情况
for (int i = 0; i < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
int left = i;
int right = i;
while (s[right + 1] >= '0' && s[right + 1] <= '9') {
right++;
}
nums.push(stoi(s.substr(left, right - left + 1)));
i = right;
} else if (s[i] == '(') {
if (i != s.size() - 1) if (s[i + 1] == '-') nums.push(0); // 不要忘记负数的情况
symbols.push(s[i]);
} else if (s[i] == ')') {
while (symbols.top() != '(') {
cal(nums, symbols);
}
symbols.pop(); // 弹出左括号
} else {
while (!symbols.empty() && (priority[s[i]] <= priority[symbols.top()])) {
cal(nums, symbols);
}
symbols.push(s[i]);
}
}
while (!symbols.empty()) {
cal(nums, symbols);
}
cout << nums.top() << endl;
}

京公网安备 11010502036488号