leetcode evaluate-reverse-polish-notation(Java)

题目:

leetcode-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

前提:输入的数组都是能正确运算的

 
思路:
     * 1、把数组从第一元素开始压入栈中
     * 2、如果是操作符,则取出栈中的前两个元素进行运算,运算后的结果压入栈中
     * 3、如果是数字,直接压入栈中即可

代码:

package com.leetcode.stack;

import java.util.Stack;

/**
 * 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
 */
public class ReverseNotation {

	/**
	 * 前提:输入的数组都是能正确运算的
	 * 
	 * 思路:
	 * 1、把数组从第一元素开始压入栈中
	 * 2、如果是操作符,则取出栈中的前两个元素进行运算,运算后的结果压入栈中
	 * 3、如果是数字,直接压入栈中即可
	 */
    public static int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length <= 0) {
        	return 0;
        }
        
        int len = tokens.length;
        Stack<String> stack = new Stack<String>();
        
        for (int i=0; i<len; i++) {
        	String str = tokens[i];
        	// 是运算符,则计算结果入栈
        	if (isOperator(str)) {
        		stack.push(String.valueOf(compute(str, stack.pop(), stack.pop())));
        		
        	// 非运算符,入栈	
        	} else {
        		stack.push(str);
        	}
        }
        
    	return parseInt(stack.pop());
    }
    
    private static int compute(String str, String second, String first) {
    	switch(str){
    		case "+":
    			return parseInt(first) + parseInt(second);
    		case "-":
    			return parseInt(first) - parseInt(second);
    		case "*":
    			return parseInt(first) * parseInt(second);
    		case "/":
    			return parseInt(first) / parseInt(second);
    		default:
    			return 0;
    	}
    }
    
    private static int parseInt(String str) {
    	return Integer.parseInt(str);
    }
    
    private static boolean isOperator(String str) {
    	return "+".equals(str) || "-".equals(str) || "*".equals(str) || "/".equals(str);
    }
	
	public static void main(String[] args) {
		String[] strArr1 = {"2", "1", "+", "3", "*"};
		System.out.println(evalRPN(strArr1));
		
		String[] strArr2 = {"4", "13", "5", "/", "+"};
		System.out.println(evalRPN(strArr2));
	}

}

猜你喜欢

转载自blog.csdn.net/zangdaiyang1991/article/details/89195926
今日推荐