【leetcode】150. 逆波兰表达式求值(evaluate-reverse-polish-notation)(栈)[中等]

链接

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

耗时

解题:10 min
题解:5 min

题意

根据 逆波兰表示法,求表达式的值。

有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

  • 整数除法只保留整数部分。
  • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

提示:

  • 1 <= tokens.length <= 1 0 4 10^4 104
  • tokens[i] 要么是一个算符("+"、"-"、"*" 或 “/”),要么是一个在范围 [-200, 200] 内的整数

思路

根据逆波兰表达式定义,设置一个栈,遍历表达式,遇到数字就把数字入栈,遇到运算符就弹出两个栈顶元素,按这个运算符计算,并将计算结果放入栈中,在遍历完后,栈中将剩余唯一一个数字,它即是答案。

时间复杂度: O ( n ) O(n) O(n)

AC代码

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

猜你喜欢

转载自blog.csdn.net/Krone_/article/details/115026710