[Leetcode] 150. Evaluate-reverse-polish-notation (stack) [medium]

link

https://leetcode-cn.com/problems/design-parking-system/

time consuming

Problem solving: 10 min
Problem solving: 5 min

Title

According to the reverse Polish notation, find the value of the expression.

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

Description:

  • Integer division only keeps the integer part.
  • The given reverse Polish expression is always valid. In other words, the expression always yields a valid value and there is no case where the divisor is zero.

prompt:

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

Ideas

According to the definition of reverse Polish expression, set up a stack, traverse the expression, put the number on the stack when encountering a number, and pop the two top elements of the stack when encountering an operator, calculate according to this operator, and put the calculation result into the stack , After traversing, there will be only one number remaining in the stack, which is the answer.

Time complexity: O (n) O(n)O ( n )

AC code

class Solution {
    
    
public:
    int evalRPN(vector<string>& tokens) {
    
    
        stack<int> st;
        for(auto x : tokens) {
    
    
            if(x.size() > 1 || isdigit(x[0])) {
    
    
                st.push(stoi(x));
            }
            else {
    
    
                int b = st.top();
                st.pop();
                int a = st.top();
                st.pop();
                int res = 0;
                if(x == "+") {
    
    
                    res = a+b;
                }
                else if(x == "-") {
    
    
                    res = a-b;
                }
                else if(x == "*") {
    
    
                    res = a*b;
                }
                else {
    
    
                    res = a/b;
                }
                st.push(res);
            }
        }
        return st.top();
    }
};

Guess you like

Origin blog.csdn.net/Krone_/article/details/115026710