zoukankan      html  css  js  c++  java
  • 【LeetCode】150.逆波兰表达式(栈+数组 两种方法,java实现)

    题目

    链接

    image-20200713122825762

    题解

    其他Java相关优化操作:

    1. 数组最大长度为tokens.length / 2 + 1
    2. switch代替if-else,效率优化
    3. Integer.parseInt代替Integer.valueOf,减少自动拆箱装箱操作

    附两种方法:

    栈实现:

    class Solution {
    	// 栈实现   8 ms	36.7 MB	
    	public static int evalRPN(String[] tokens) {
    		Stack<Integer> numStack = new Stack<>();
    		Integer op1, op2;
    		for (String s : tokens) {
    			switch (s) {
    			case "+":
    				op2 = numStack.pop();
    				op1 = numStack.pop();
    				numStack.push(op1 + op2);
    				break;
    			case "-":
    				op2 = numStack.pop();
    				op1 = numStack.pop();
    				numStack.push(op1 - op2);
    				break;
    			case "*":
    				op2 = numStack.pop();
    				op1 = numStack.pop();
    				numStack.push(op1 * op2);
    				break;
    			case "/":
    				op2 = numStack.pop();
    				op1 = numStack.pop();
    				numStack.push(op1 / op2);
    				break;
    			default:
    				numStack.push(Integer.valueOf(s));
    				break;
    			}
    		}
    		return numStack.pop();
    	}
    }
    

    数组:

    class Solution {
    	//纯数组模拟栈实现(推荐)   3 ms	36 MB
    	public static int evalRPN(String[] tokens) {
    		int[] numStack = new int[tokens.length / 2 + 1];
    		int index = 0;
    		for (String s : tokens) {
    			switch (s) {
    			case "+":
    				numStack[index - 2] += numStack[--index];
    				break;
    			case "-":
    				numStack[index - 2] -= numStack[--index];
    				break;
    			case "*":
    				numStack[index - 2] *= numStack[--index];
    				break;
    			case "/":
    				numStack[index - 2] /= numStack[--index];
    				break;
    			default:
    				// numStack[index++] = Integer.valueOf(s);
    				//valueOf改为parseInt,减少自动拆箱装箱操作
    				numStack[index++] = Integer.parseInt(s);
    				break;
    			}
    		}
    		return numStack[0];
    	}
    }
    
  • 相关阅读:
    汉诺塔问题合集之汉诺塔6
    汉诺塔问题合集之汉诺塔5
    接口和抽象类有什么区别
    Java版本:JDK8的十大新特性介绍
    Linux的常用命令
    行为型模式——策略模式
    shell 后台执行命令
    ORA-01034:oracle不可用 的解决方法
    ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法
    linux下启动oracle
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13307973.html
Copyright © 2011-2022 走看看