• 150. Evaluate Reverse Polish Notation


    问题描述:

    Evaluate the value of an arithmetic expression in Reverse Polish Notation.

    Valid operators are +-*/. Each operand may be an integer or another expression.

    Note:

    • Division between two integers should truncate toward zero.
    • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

    Example 1:

    Input: ["2", "1", "+", "3", "*"]
    Output: 9
    Explanation: ((2 + 1) * 3) = 9
    

    Example 2:

    Input: ["4", "13", "5", "/", "+"]
    Output: 6
    Explanation: (4 + (13 / 5)) = 6
    

    Example 3:

    Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
    Output: 22
    Explanation: 
      ((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

    解题思路:

    这个是操作符在后面的形式。

    我们可以用栈来辅助进行计算:

      当遇见数字字符串时,需要转换成int并进行压栈;

      当遇见操作符字符串时,取出栈顶前两个元素,计算后将结果压栈

    代码:

    class Solution {
    public:
        int evalRPN(vector<string>& tokens) {
            stack<int> stk;
            int ret = 0;
            for(int i = 0; i < tokens.size(); i++){
                if(tokens[i].size() == 1){
                    int isOp = isOperator(tokens[i]);
                    if(isOp >= 0){
                        int a = stk.top();
                        stk.pop();
                        int b = stk.top();
                        stk.pop();
                        if(isOp == 0){
                            stk.push(a+b);
                        }else if(isOp == 1){
                            stk.push(b-a);
                        }else if(isOp == 2){
                            stk.push(b*a);
                        }else if(isOp == 3){
                            stk.push(b / a);
                        }
                        continue;
                    }
                }
                int num = stoi(tokens[i]);
                stk.push(num);
            }
            return stk.top();
        }
    private:
        int isOperator(string s){
            if(s == "+")
                return 0;
            if(s == "-")
                return 1;
            if(s == "*")
                return 2;
            if(s == "/")
                return 3;
            return -1;
        }
    };
  • 相关阅读:
    Vue 函数
    VUE 基础语法
    C# txt文件操作
    C# 添加应用程序包
    Js 倒计时跳转
    Redis集群(主从集群)(一)
    JAVA基础总结001(《JAVA核心技术》)
    Linux学习001——文件和用户
    Linux——ELK集群搭建
    Linux安装jdk
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9227088.html
Copyright © 2020-2023  润新知