栈的应用——表达式求值

栈的应用——表达式求值

题目描述

给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。
注意:

  • 数据保证给定的表达式合法。
  • 题目保证符号 - 只作为减号出现,不会作为负号出现,例如,-1+2,(2+2)*(-(1+1)+2) 之类表达式均不会出现。
  • 题目保证表达式中所有数字均为正整数。
  • 题目保证表达式在中间计算过程以及结果中,均不超过 2^31−1。
  • 题目中的整除是指向 0 取整,也就是说对于大于 0 的结果向下取整,例如 5/3=1,对于小于 0 的结果向上取整,例如5/(1−4)=−1。
  • C++和Java中的整除默认是向零取整;Python中的整除//默认向下取整,因此Python的eval()函数中的整除也是向下取整,在本题中不能直接使用。
    原题链接:https://www.acwing.com/problem/content/description/3305/

解题思路

首先考虑符号的优先级 “)” > “/” == “*” > “+” == “-” > “(”
因为之后有优先级的比较所以我这里用一个hash表来存储优先级的高低

unordered_map<char, int> pr{
     {
     '+', 1}, {
     '-', 1}, {
     '*', 2}, {
     '/', 2}};

明确思路:
STEP 1:先将算术表达式转换成后缀表达式。
STEP 2:然后对该后缀表达式求值。

完整代码

#include 
#include 
#include 
#include 
#include 

using namespace std;

stack<int> num;
stack<char> op;

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);
}

int main()
{
     
    unordered_map<char, int> pr{
     {
     '+', 1}, {
     '-', 1}, {
     '*', 2}, {
     '/', 2}};
    string str;
    cin >> str;
    for (int i = 0; i < str.size(); i ++ )
    {
     
        auto c = str[i];
        if (isdigit(c))
        {
     
            int x = 0, j = i;
            while (j < str.size() && isdigit(str[j]))
                x = x * 10 + str[j ++ ] - '0';
            //这里是因为我们将数字差分为字符所以12会被差分为'1'和'2'
            i = j - 1;
            num.push(x);
        }
        else if (c == '(') op.push(c);
        //遇到左括号直接入栈
        else if (c == ')')
        {
     
            while (op.top() != '(') eval();
            op.pop();
        }
        else
        {
     
            while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
            op.push(c);
        }
    }
    while (op.size()) eval();
    cout << num.top() << endl;
    return 0;
}

你可能感兴趣的:(笔记,栈,数据结构)