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();
        }
    }
  • 相关阅读:
    Protocol Buffer详解
    RPC进阶篇
    RPC基础篇
    测试控制器
    更加简洁的tableview
    storyboard中Unwind segue使用
    IOS开发Apache服务器搭建
    IOS多线程操作
    IOS使用Svn的trunk、branches、tag分别的侧重
    在设计IOSapp时为了代码的扩展性可可维护性需要遵守的原则
  • 原文地址:https://www.cnblogs.com/lc1475373861/p/12007106.html
Copyright © 2011-2022 走看看