Created
May 25, 2021 09:50
-
-
Save vrat28/cec61c2e5cf43313da46ba89e050f148 to your computer and use it in GitHub Desktop.
Reverse Polish Notation (Java -Lambdas)
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
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice