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

    Some examples:

      ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
      ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
    public class Solution {
        //对于逆波兰式,一般都是用栈来处理,依次处理字符串,
    
        //如果是数值,则push到栈里面
    
        //如果是操作符,则从栈中pop出来两个元素,计算出值以后,再push到栈里面,
    
        //则最后栈里面剩下的元素即为所求。
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack=new Stack<Integer>();
            for(int i=0;i<tokens.length;i++){
                if(!isDigit(tokens[i])){
                    stack.push(Integer.parseInt(tokens[i]));
                    continue;
                }
                int num1=stack.pop();
                int num2=stack.pop();
                if(tokens[i].equals("-")){
                    stack.push(num2-num1);
                }
                if(tokens[i].equals("+")){
                    stack.push(num1+num2);
                }
                if(tokens[i].equals("*")){
                    stack.push(num1*num2);
                }
                if(tokens[i].equals("/")){
                    stack.push(num2/num1);
                }
            }
            return stack.pop();
        }
        public boolean isDigit(String s){
            if(s.equals("-")||s.equals("+")||s.equals("*")||s.equals("/")) return true;
            return false;
        }
    }
  • 相关阅读:
    BZOJ 3744 Gty的妹子序列
    BZOJ 3872 Ant colony
    BZOJ 1087 互不侵犯
    BZOJ 1070 修车
    BZOJ 2654 tree
    BZOJ 3243 向量内积
    1003 NOIP 模拟赛Day2 城市建设
    CF865D Buy Low Sell High
    CF444A DZY Loves Physics
    Luogu 4310 绝世好题
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4694645.html
Copyright © 2011-2022 走看看