zoukankan      html  css  js  c++  java
  • leetcode150- Evaluate Reverse Polish Notation- medium

    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,是符号,进行处理。吐两个数n1,n2出来做算术,小心要n2 +-*/ n1,因为stack的原因。

    小改进:判断是不是符号可以用 String operators = "+-*/"; if (operators.contains(token)) {} 来写,优雅一点。

    class Solution {
        public int evalRPN(String[] tokens) {
            
            if (tokens == null || tokens.length == 0) {
                return 0;
            }
            Stack<Integer> stack = new Stack<>();
            
            for (int i = 0; i < tokens.length; i++) {
                if (!isOperator(tokens[i])) {
                    stack.push(Integer.parseInt(tokens[i]));
                } else {
                    int i1 = stack.pop();
                    int i2 = stack.pop();
                    if (tokens[i].equals("+")) {
                        stack.push(i2 + i1);
                    } else if (tokens[i].equals("-")) {
                        stack.push(i2 - i1);
                    } else if (tokens[i].equals("*")) {
                        stack.push(i2 * i1);
                    } else if (tokens[i].equals("/")) {
                        stack.push(i2 / i1);
                    }
                }
            }
            return stack.pop();
        }
        
        private boolean isOperator(String s) {
            return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
        }
    }
  • 相关阅读:
    Spring注解
    [Exception Android 22]
    Android中Word转Html
    [Exception Android 20]
    POI-word转html
    【JS设计模式】装饰者模式
    C语言中的传值调用
    Spring Aop基础总结
    Android开发-状态栏着色原理和API版本号兼容处理
    9.12測试(二)——国际象棋
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7836704.html
Copyright © 2011-2022 走看看