当前位置:网站首页>Sword finger offer II 036 Postfix Expression

Sword finger offer II 036 Postfix Expression

2022-06-11 08:56:00 Drag is me

leetcode Force button to brush questions and punch in

subject : The finger of the sword Offer II 036. Postfix expression
describe : according to Reverse Polish notation , Find the calculation result of the suffix expression .

Valid operators include +、-、*、/ . Each operand can be an integer , It can also be another inverse Polish expression .

explain :

Integer division keeps only the integer part .
Given an inverse Polish expression is always valid . let me put it another way , The expression always yields a valid number and does not have a divisor of 0 The situation of .
The inverse Polish expression has two main advantages :

There is no ambiguity in the expression after removing the brackets , Even if the above formula is written as 1 2 + 3 4 + * You can also calculate the correct result according to the order .
It is suitable for stack operation : When it comes to numbers, it's on the stack ; When you encounter an operator, you take out two numbers at the top of the stack to calculate , And push the results into the stack .

Their thinking

1、 All the questions are told to use the stack ;
2、 Determine whether the string is a number ;

Source code ##

class Solution {
    
public:
    bool isnum(string s) {
    
        return !(s == "+" || s == "-" || s == "*" || s == "/");
    }
    int evalRPN(vector<string>& tokens) {
    
        stack<int>s;
        int pre1 = 0, pre2 = 0, ans = 0, temp = 0;
        for (int i = 0; i < tokens.size(); ++i) {
    
            if (isnum(tokens[i])) {
    
                temp = stoi(tokens[i]);
                s.push(temp);
            } else {
    
                pre1 = s.top();
                s.pop();
                pre2 = s.top();
                s.pop();
                if (tokens[i][0] == '+') {
    
                s.push(pre1 + pre2);
                } else if (tokens[i][0] == '-') {
    
                s.push(pre2 - pre1);
                } else if (tokens[i][0] == '*') {
    
                s.push(pre1 * pre2);
                } else if (tokens[i][0] == '/') {
    
                s.push(pre2 / pre1);
                }   
            }
        }
        return s.top();
    }
};

原网站

版权声明
本文为[Drag is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110855010585.html