https://leetcode.com/problems/evaluate-reverse-polish-notation/
- Stack
- Array
Push operands on a stack and apply operators when they appear.
O(n)
O(n)
import java.util.*;
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
switch (token) {
case "+": stack.push(stack.pop() + stack.pop()); break;
case "-": {
int b = stack.pop();
int a = stack.pop();
stack.push(a - b);
break;
}
case "*": stack.push(stack.pop() * stack.pop()); break;
case "/": {
int b = stack.pop();
int a = stack.pop();
stack.push(a / b);
break;
}
default: stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}