Reverse Polish expression evaluation (stack)

Reverse Polish expression evaluation

Source: LeetCode
topic link: https://leetcode-cn.com/problems/evaluate-reverse-polish-notation


Problem Description

Evaluates the expression in reverse Polish notation.
Difficulty: Moderate

Valid operators include +, -, *, /. Each operand can be an integer or another reverse Polish expression.

illustrate:

  • Integer division keeps only the integer part.
  • The given reverse Polish expression is always valid. In other words, the expression will always result in a valid value and there will be no division by zero.

Sample1

输入:tokens = ["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9

Sample2

输入:tokens = ["4","13","5","/","+"]
输出:6
解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6

Sample3

输入:tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
输出:22
解释:
该算式转化为常见的中缀算术表达式为:
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

Hint

1 <= tokens.length <= 1 0 4 10^4 104
tokens[i] is either an operator ("+", "-", "*" or "/"), or an integer in the range [-200, 200]


Solution

First of all, we need to know what the reverse Polish expression is. The reverse Polish expression is a kind of suffix expression. The so-called suffix means that the operator is written behind.

For example, the expressions we usually use are all infix expressions, in the form of ( 1 + 2 ) * ( 3 + 4 ), and the corresponding postfix expression of this expression is ( ( 1 2 + ) ( 3 4 + ) * ), I believe that friends who have studied data structures know how to calculate and evaluate postfix expressions.

Since it is a learning algorithm, let's consider the problem of evaluating the reverse Polish expression , how to use a program to solve it better!


insert image description here

solution strategy

1. First, you need to write a function that converts a string into a value. We name this function the convert function. It should be noted that when converting a negative string into a value, you should pay attention to the handling of the negative sign .
2. Reverse Polish formula is especially suitable for evaluation with the data structure of the stack . When a number is encountered, it is pushed onto the stack; when an operator is encountered, the two numbers on the top of the stack are taken out for calculation, and the result is pushed onto the stack. One thing to note is that when performing a subtraction (or division operation), you need to figure out who the subtrahend and the minuend are (who are the divisor and the dividend). When a minus sign is encountered, the top element of the stack is the subtrahend, and the new top element after the top element is popped is the minuend .
3. Finally, if there is only one element left in the stack, this element is the answer .


When you really understand the structure of the stack , this problem will be solved. The idea of ​​this question can be understood by referring to the figure below.


insert image description here


Code

class Solution {
    
    
public:
    int evalRPN(vector<string>& tokens) {
    
    
        int len= tokens.size();
        stack<int>st;
        int res=0;
        int a,b,type;
        for(int i=0;i<len;i++)
        {
    
    
            type=oper(tokens[i]); //判断符号的类型,是数字,还是运算符?
            if(type==0)
            {
    
    
                st.push(convert(tokens[i]));
            }
            else if(type==1)
            {
    
    
                a=st.top(); //取出栈顶元素
                st.pop();
                b=st.top();
                st.pop();
                res=a+b;
                st.push(res);
            }
            else if(type==2)
            {
    
    
                a=st.top();
                st.pop();
                b=st.top();
                st.pop();
                res=b-a;
                st.push(res);
            }
            else if(type==3)
            {
    
    
                a=st.top();
                st.pop();
                b=st.top();
                st.pop();
                res=a*b;
                st.push(res);
            }
            else if(type==4)
            {
    
    
                a=st.top();
                st.pop();
                b=st.top();
                st.pop();
                res=b/a;
                st.push(res);
            }
        }
        return st.top();
        
    }

    int oper(string s) //判断符号类型
    {
    
    
        if(s=="+")
        return 1;
        else if(s=="-")
        return 2;
        else if(s=="*")
        return 3;
        else if(s=="/")
        return 4;
        else return 0;
    }

    int convert(string s) //将String类型的数字转化为int类型
    {
    
    
        int res=0;
        int len=s.length();
        if(s[0]!='-')
        {
    
    
            for(int i=0;i<len;i++)
            {
    
    
            res=res*10+(s[i]-'0');
            }
        }
        else
        {
    
    
            for(int i=1;i<len;i++) //如果为负数,则从s[1]开始计算
            {
    
    
                res=res*10+(s[i]-'0');
            }
            res*=-1;
        }
        return res;
    }
};

    /*
    *
    *  ┏┓   ┏┓+ +
    * ┏┛┻━━━┛┻┓ + +
    * ┃       ┃
    * ┃   ━   ┃ ++ + + +
    *  ████━████+
    *  ◥██◤ ◥██◤ +
    * ┃   ┻   ┃
    * ┃       ┃ + +
    * ┗━┓   ┏━┛
    *   ┃   ┃ + + + +Code is far away from  
    *   ┃   ┃ + bug with the animal protecting
    *   ┃    ┗━━━┓ 神兽保佑,代码无bug 
    *   ┃        ┣┓
    *    ┃        ┏┛
    *     ┗┓┓┏━┳┓┏┛ + + + +
    *    ┃┫┫ ┃┫┫
    *    ┗┻┛ ┗┻┛+ + + +
    */





Finally, thank you for your study~

Guess you like

Origin blog.csdn.net/weixin_43800577/article/details/115025700