150. Evaluate Reverse Polish Notation
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack();
for(String token: tokens) {
if("+-*/".contains(token)) {
int b = stack.pop();
int a = stack.pop();
stack.add(operate(token, a, b));
} else {
stack.add(Integer.valueOf(token));
}
}
return stack.pop();
}
private int operate(String operation, int a, int b) {
if("+".equals(operation)) return a+b;
if("-".equals(operation)) return a-b;
if("*".equals(operation)) return a*b;
if("/".equals(operation)) return a/b;
return 0;
}
}