题目描述
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
要点
前缀表达式(波兰表达式):"+ - A * B C D",中缀表达式为:“A - B * C + D”;后缀表达式(逆波兰表达式):“A B C * - D +”,后缀表达式的优点是显而易见的,编译器在处理时候按照从左至右的顺序读取逆波兰表达式,遇到运算对象直接压入堆栈,遇到运算符就从堆栈提取后进的两个对象进行计算,这个过程正好符合了计算机计算的原理。
class Solution{
public int evalRPN(String[] tokens){
if(tokens.length == 0){
return 0;
}
int res = 0;
Stack<Integer> stack = new Stack<>();
for(int i = 0;i < tokens.length;i++){
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")){
int b = stack.pop();
int a = stack.pop();
if(tokens[i].equals("+")){
res = a + b;
}
else if(tokens[i].equals("-")){
res = a - b;
}
else if(tokens[i].equals("*")){
res = a * b;
}
else if(tokens[i].equals("/")){
res = a / b;
}
stack.push(res);
}
else{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}