Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- private static final String[] ops = {"+", "-", "*", "/"};
- /**
- *
- * T: O(n), S: O(n)
- *
- * @param tokens: The Reverse Polish Notation
- * @return: the value
- */
- public int evalRPN(String[] tokens) {
- Stack<Integer> stack = new Stack<Integer>();
- for(String token : tokens) {
- if(isOp(token)) {
- int num2 = stack.pop();
- int num1 = stack.pop();
- String op = token;
- stack.push(eval(num1, num2, op));
- } else {
- stack.push(new Integer(token));
- }
- }
- return stack.peek();
- }
- private int eval(int num1, int num2, String op) {
- switch(op) {
- case "+":
- return num1 + num2;
- case "-":
- return num1 - num2;
- case "*":
- return num1 * num2;
- case "/":
- return num1 / num2;
- }
- throw new IllegalArgumentException();
- }
- private boolean isOp(String token) {
- for(String op : ops) {
- if(op.equals(token)) {
- return true;
- }
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment