思路:栈实现
判断当前元素是否是加减乘除,是的话弹出下两个元素,进行运算
不是则压入栈
import java.util.*;
public class Solution{
public static int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0)
return 0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")) {
int x = stack.pop();
int y = stack.pop();
stack.push(calculate(y, x, tokens[i]));
} else
stack.push(Integer.parseInt(tokens[i]));
}
return stack.pop();
}
private static int calculate(int x, int y, String token) {
if (token.equals("+"))
return x + y;
else if (token.equals("-"))
return x - y;
else if (token.equals("*"))
return x * y;
else if (token.equals("/"))
return x / y;
else
return 0;
}
}