Evaluate the value of an arithmetic expression in.
Valid operators are+
,-
,*
,/
. Each operand may be an integer or another expression.
class Solution {
private boolean isNum(String token) {
if ("+-*/".contains("" + token.charAt(0)) && token.length() == 1) {
return false;
}
return true;
}
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String str : tokens) {
if (isNum(str)) {
stack.push(Integer.parseInt(str));
} else {
int op2 = stack.pop(), op1 = stack.pop();
switch (str) {
case "+":
stack.push(op1 + op2);
break;
case "-":
stack.push(op1 - op2);
break;
case "*":
stack.push(op1 * op2);
break;
default:
stack.push(op1 / op2);
}
}
}
return stack.pop();
}
}
时空复杂度都是O(n).