Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 25, 2021 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/cec61c2e5cf43313da46ba89e050f148 to your computer and use it in GitHub Desktop.
Save vrat28/cec61c2e5cf43313da46ba89e050f148 to your computer and use it in GitHub Desktop.
Reverse Polish Notation (Java -Lambdas)
class Solution {
private static final Map<String, BiFunction<Integer, Integer, Integer>> OPERATIONS = new HashMap<>();
// Ensure this only gets done once for ALL test cases.
static {
OPERATIONS.put("+", (a, b) -> a + b);
OPERATIONS.put("-", (a, b) -> a - b);
OPERATIONS.put("*", (a, b) -> a * b);
OPERATIONS.put("/", (a, b) -> a / b);
}
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (!OPERATIONS.containsKey(token)) {
stack.push(Integer.valueOf(token));
continue;
}
int number2 = stack.pop();
int number1 = stack.pop();
BiFunction<Integer, Integer, Integer> operation;
operation = OPERATIONS.get(token);
int result = operation.apply(number1, number2);
stack.push(result);
}
return stack.pop();
}
}
@nityanandrai10
Copy link

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment