zoukankan      html  css  js  c++  java
  • LeetCode每日一道(2)

     问题描述:

      

    计算逆波兰式(后缀表达式)的值
    运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
    例如:
      ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
    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

    思路:
      考虑使用栈结构实现,在遇到运算法号的时候直接取出栈顶的两个元素进行运算操作,然后把运算结果重新压回栈,
      最后栈剩下的中元素为目标结果。
    import java.util.Stack;
    public class Solution {
        public int evalRPN(String[] tokens) {
            if(tokens==null){
                return 0;
            }
            Stack<Integer> stack = new Stack<Integer>();
            for(int i = 0;i < tokens.length; i++){
                    if(tokens[i].equals("+")){
                        int a = Integer.valueOf(stack.pop());
                        int b = Integer.valueOf(stack.pop());
                        stack.push(a+b);
                    }else if(tokens[i].equals("-")){
                        int a = Integer.valueOf(stack.pop());
                        int b = Integer.valueOf(stack.pop());
                        stack.push(b-a);
                    }else if(tokens[i].equals("*")){
                        int a = Integer.valueOf(stack.pop());
                        int b = Integer.valueOf(stack.pop());
                        stack.push(a*b);
                    }else if(tokens[i].equals("/")){ 
                        int a = Integer.valueOf(stack.pop());
                        int b = Integer.valueOf(stack.pop());
                        stack.push(b/a);
                    }else{
                        stack.push(Integer.valueOf(tokens[i]));
                    }
            }
            return stack.pop();
        }
    }
  • 相关阅读:
    测试72.思维好题
    pbds:STL平衡树
    测试69。这场因为轻视少了很多分。
    C++ 中的四种类型转换
    C++ 中的static关键字
    codeforces 1269 E K Integers
    P4556 [Vani有约会]雨天的尾巴 (线段树合并)
    P3521 [POI2011]ROT-Tree Rotations (线段树合并)
    codeforces 600E E. Lomsat gelral (线段树合并)
    线段树合并的一些题
  • 原文地址:https://www.cnblogs.com/lc1475373861/p/12007106.html
Copyright © 2011-2022 走看看