xiutianxiudi

Lintcode 424. Evaluate Reverse Polish Notation

Oct 18th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. public class Solution {
  2.  
  3.     private static final String[] ops = {"+", "-", "*", "/"};
  4.  
  5.     /**
  6.      *
  7.      * T: O(n), S: O(n)
  8.      *
  9.      * @param tokens: The Reverse Polish Notation
  10.      * @return: the value
  11.      */
  12.     public int evalRPN(String[] tokens) {
  13.         Stack<Integer> stack = new Stack<Integer>();
  14.  
  15.         for(String token : tokens) {
  16.             if(isOp(token)) {
  17.                 int num2 = stack.pop();
  18.                 int num1 = stack.pop();
  19.                 String op = token;
  20.                 stack.push(eval(num1, num2, op));
  21.             } else {
  22.                 stack.push(new Integer(token));
  23.             }
  24.         }
  25.         return stack.peek();
  26.     }
  27.  
  28.     private int eval(int num1, int num2, String op) {
  29.         switch(op) {
  30.             case "+":
  31.                 return num1 + num2;
  32.             case "-":
  33.                 return num1 - num2;
  34.             case "*":
  35.                 return num1 * num2;
  36.             case "/":
  37.                 return num1 / num2;
  38.         }
  39.         throw new IllegalArgumentException();
  40.     }
  41.  
  42.     private boolean isOp(String token) {
  43.         for(String op : ops) {
  44.             if(op.equals(token)) {
  45.                 return true;
  46.             }
  47.         }
  48.         return false;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment