【算法决】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

思路:使用数据结构-stack,循环遍历数组中的元素,当是数字的时候将它压入stack,当是操作符的时候,分别弹出stack中的两个元素,然后根据计算符计算结果并将结果重新压入stack

import java.util.Stack;

public class Solution {
	
	public static void main(String[] args){
		String[] tokens = {"2","1","+","3","*"};
		System.out.println(evalRPN(tokens));
		
	}
	
	public static int evalRPN(String[] tokens){
		int return_value = 0;
		String notation = "+-*/";
		Stack<String> stack = new Stack<String>();
		for(String t : tokens){
			if(!notation.contains(t)){
				stack.push(t);
			}
			else{
			int index = notation.indexOf(t);
			int integer1 = Integer.valueOf(stack.pop());
			int integer2 = Integer.valueOf(stack.pop());
			switch (index){
				case 0:
					stack.push(String.valueOf(integer1+integer2));
					break;
				case 1:
					stack.push(String.valueOf(integer2-integer1));
					break;
				case 2:
					stack.push(String.valueOf(integer1*integer2));
					break;
				case 3:
					stack.push(String.valueOf(integer2/integer1));
					break;
			}
					
			}
			
		}
		
		return_value = Integer.valueOf(stack.pop());
		
		
		
		return return_value;
		
	}

}



你可能感兴趣的:(java,LeetCode,算法)