zoukankan      html  css  js  c++  java
  • Leetcode 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.

    Some examples:

      ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
      ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

    此题是求解后缀表达式,题目比较简单,开一个数据stack即可,此题的改进版本是引入括号,此时要开一个数据stack和运算符stack
    bool isOperator(string& op){
        if(op == "+" ||  op == "-" || op == "*" || op == "/") return true;
        else return false;
    }
    
    int calc(int a, int b, char op){
        switch(op){
            case '+':return a+b;
            case '-':return a-b;
            case '*':return a*b;
            case '/':return a/b;
        }
    }
    
    int evalRPN(vector<string> &tokens){
        stack<int> num;
        for(int i = 0 ; i < tokens.size(); ++ i){
            if(!isOperator(tokens[i])){
                num.push(atoi(tokens[i].c_str()));
            }else{
                int num2 = num.top(); num.pop();
                int num1 = num.top(); num.pop();
                char op = tokens[i][0];
                num.push(calc(num1,num2,op));
            }
        }
        return num.top();
    }
     
  • 相关阅读:
    Windows10 搭建 ElasticSearch 集群服务
    python开发目录
    nohup命令使用
    shell脚本概述
    关于ELK
    keepalived+DR
    shell脚本中awk的用法
    shell脚本中sed的用法
    shell脚本中grep的用法
    shell检测入侵与邮件报警
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3794372.html
Copyright © 2011-2022 走看看