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
思路:
- 用棧記錄數(shù)組前面未進行運算的值。
- 遍歷數(shù)組。遇到數(shù)字直接入棧;遇到運算符號,出棧兩個數(shù)字進行運算,將結(jié)果入棧。
- 最后返回棧中元素就是表達式計算結(jié)果。
- 注意除法和減法,出棧數(shù)字的運算順序。
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
for (String val : tokens) {
if (val.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (val.equals("-")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b - a);
} else if (val.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (val.equals("/")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b / a);
} else if (Integer.valueOf(val) >= 0) {
stack.push(Integer.valueOf(val));
} else {
return -1;
}
}
return stack.pop();
}