acwing3302. 表达式求值(双栈模拟)

在这里插入图片描述## 思路

  1. 这题的思路核心就是通过使用两个栈,一个是存放操作数的栈,一个是存放 运算符的栈,通过这两个栈进行模拟。

代码

#include<iostream>
#include<map>
#include<stack>
using namespace std;
map<char, int> isp, icp;
const char opers[6] = {
    
    '+', '-', '*', '/', '(', ')'};
const int isps[6] = {
    
    3, 3, 5, 5, 1, 6}, icps[6] = {
    
    2, 2, 4, 4, 6, 1};
void init() {
    
    
    for(int i = 0; i < 6; ++i) isp[opers[i]] = isps[i], icp[opers[i]] = icps[i];
}

void calc(stack<char>& ops, stack<int>& nums) {
    
    
    int b = nums.top(); nums.pop();
    int a = nums.top(); nums.pop();
    char op = ops.top(); ops.pop();
    int t;
    if(op == '+') t = a + b;
    else if(op == '-') t = a - b;
    else if(op == '*') t = a * b;
    else t = a / b;
    nums.push(t);
}

int calculate(string s) {
    
    
    s = "(" + s + ")";
    stack<char> ops;
    stack<int>  nums;
    int n = s.size();
    for(int i = 0; i < n; ++i) {
    
    
        if('0' <= s[i] && s[i] <= '9') {
    
    
            int t = s[i] - '0';
            for(int j = i + 1; j < n; ++j) {
    
    
                if('0' <= s[j] && s[j] <= '9') t = t * 10 + (s[j] - '0');
                else {
    
    
                    i = j - 1;
                    nums.push(t);
                    break;
                }
            }
        } else if(s[i] == ' ') continue;
        else {
    
    
            if(ops.empty() || isp[ops.top()] < icp[s[i]]) ops.push(s[i]);
            else if(isp[ops.top()] == icp[s[i]]) ops.pop();
            else {
    
    
                calc(ops, nums);
                i--;
            }
        }
    }
    return nums.top();
}

int main() {
    
    
    init();
    string s;
    cin >> s;
    cout << calculate(s);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34261446/article/details/121488698