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.*;
public class Solution {
public static HashSet<String> opSet = new HashSet<String>();
static{
opSet.add("+");
opSet.add("-");
opSet.add("*");
opSet.add("/");
}
public int evalRPN(String[] tokens) {
Stack<Integer> numStack = new Stack<>();
for(int i = 0 ;i < tokens.length; i ++){
if(opSet.contains(tokens[i])){
//是操作符
Integer num1;
Integer num2;
switch(tokens[i]){
case "+" :
num1 = numStack.pop();
num2 = numStack.pop();
numStack.push(num1 + num2);
break;
case "-" :
num1 = numStack.pop();
num2 = numStack.pop();
numStack.push(num2 - num1);
break;
case "*" :
num1 = numStack.pop();
num2 = numStack.pop();
numStack.push(num1 * num2);
break;
case "/" :
num1 = numStack.pop();
num2 = numStack.pop();
numStack.push(num2 / num1);
break;
default:
break;
}
}else{
//是操作数
numStack.push(Integer.parseInt(tokens[i]));
}
}
return numStack.pop();
}
}