原题网址:https://leetcode.com/problems/evaluate-reverse-polish-notation/
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
方法:使用栈保存操作数。
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(int i=0; i<tokens.length; i++) {
if ("+".equals(tokens[i])) {
int b = stack.pop();
int a = stack.pop();
stack.push(a+b);
} else if ("-".equals(tokens[i])) {
int b = stack.pop();
int a = stack.pop();
stack.push(a-b);
} else if ("*".equals(tokens[i])) {
int b = stack.pop();
int a = stack.pop();
stack.push(a*b);
} else if ("/".equals(tokens[i])) {
int b = stack.pop();
int a = stack.pop();
stack.push(a/b);
} else {
stack.push(Integer.parseInt(tokens[i], 10));
}
}
return stack.pop();
}
}