zoukankan      html  css  js  c++  java
  • LeetCode 150. Evaluate Reverse Polish Notation

    原题链接在这里:https://leetcode.com/problems/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, 遇到数字就压栈,遇到运算符就先pop() op2, 再pop() op1, 按op1 运算符op2 计算,得出结果压回栈,最后站内剩下的就是结果.

    Time Complexity: O(n). n = tokens.length.

    Space: O(n).

    AC Java:

     1 class Solution {
     2     public int evalRPN(String[] tokens) {
     3         if(tokens == null || tokens.length == 0){
     4             return 0;
     5         }
     6         
     7         Stack<Integer> stk = new Stack<Integer>();
     8         for(int i = 0; i<tokens.length; i++){
     9             if(tokens[i].equals("+")){
    10                 int op2 = stk.pop();
    11                 int op1 = stk.pop();
    12                 stk.push(op1+op2);
    13             }else if(tokens[i].equals("-")){
    14                 int op2 = stk.pop();
    15                 int op1 = stk.pop();
    16                 stk.push(op1-op2);
    17             }else if(tokens[i].equals("*")){
    18                 int op2 = stk.pop();
    19                 int op1 = stk.pop();
    20                 stk.push(op1*op2);
    21             }else if(tokens[i].equals("/")){
    22                 int op2 = stk.pop();
    23                 int op1 = stk.pop();
    24                 stk.push(op1/op2);
    25             }else{
    26                 stk.push(Integer.valueOf(tokens[i]));
    27             }
    28         }
    29         
    30         return stk.pop();
    31     }
    32 }

    跟上Basic Calculator.

  • 相关阅读:
    SpringCloudStream实例
    Gateway环境搭建,通过YML文件配置
    Hystrix图形化监控
    Hystrix服务降级
    SpringBootのRedis
    springboot之缓存
    springboot整合JPA
    留言板
    Python 京东口罩监控+抢购
    2019年 自我总结
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825017.html
Copyright © 2011-2022 走看看