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("/");
        }
    }
  • 相关阅读:
    android图片优化
    Android多线程断点下载的代码流程解析
    文件下载
    图片上传
    DomHelper
    SAX解析类:SaxHelper
    Android开发之画图的实现
    匿名内部类与equals之学习要扎实
    方法构造和方法重载之奥特曼与大boss之战
    排序之那些令人凌乱的那些小程序
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7836704.html
Copyright © 2011-2022 走看看