-
-
Save InterviewBytes/cf21e6a9ff3541b52693c16eaa96aa11 to your computer and use it in GitHub Desktop.
Evaluate Reverse Polish Notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.rpn; | |
import java.util.ArrayDeque; | |
import java.util.Deque; | |
import java.util.HashSet; | |
import java.util.Set; | |
public class Solution { | |
private static final Set<String> OPERATORS = new HashSet<>(); | |
static { | |
OPERATORS.add("+"); | |
OPERATORS.add("-"); | |
OPERATORS.add("*"); | |
OPERATORS.add("/"); | |
} | |
public int evalRPN(String[] tokens) { | |
Deque<Integer> stack = new ArrayDeque<>(); | |
for (String token : tokens) { | |
if (OPERATORS.contains(token)) { | |
int a = stack.pop(); | |
int b = stack.pop(); | |
switch (token) { | |
case "+": | |
stack.push(a + b); | |
break; | |
case "-": | |
stack.push(b - a); | |
break; | |
case "*": | |
stack.push(a * b); | |
break; | |
case "/": | |
stack.push(b / a); | |
break; | |
default: | |
break; | |
} | |
} else { | |
stack.push(Integer.valueOf(token)); | |
} | |
} | |
return stack.pop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment