Evaluate Reverse Polish Notation
Total Accepted: 5353 Total Submissions: 28309Evaluate 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 int evalRPN(String[] tokens) {
Stack<Integer> st = new Stack<Integer>();
int opr;
for (String str : tokens) {
switch (str) {
case "+":
st.push(st.pop() + st.pop());
break;
case "-":
opr = st.pop();
st.push(st.pop() - opr);
break;
case "/":
opr = st.pop();
st.push(st.pop() / opr);
break;
case "*":
st.push(st.pop() * st.pop());
break;
default:
st.push(Integer.parseInt(str));
}
}
return st.pop();
}