逆波兰表达式,不需要括号的表达式。好像就是从前数据结构书上学过的中缀表达式。
wikipedia上很好地解释了运算步骤,就是用stack。遇到符号就pop,结果push回去。
https://en.wikipedia.org/wiki/Reverse_Polish_notation
唯一要注意的是减号、除号的pop出栈的顺序。
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (tokens[i].equals("-")) {
stack.push(-stack.pop() + stack.pop());
} else if (tokens[i].equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (tokens[i].equals("/")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2 / num1);
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}