kt: add «150. Evaluate Reverse Polish Notation»

URL:	https://leetcode.com/problems/evaluate-reverse-polish-notation/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-08 23:25:40 +01:00
parent d7e8cc6f46
commit 589ae3bcea
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,29 @@
class Solution {
private fun getFunction(op: String): (Int, Int) -> Int =
when (op) {
"+" -> Int::plus
"-" -> Int::minus
"*" -> Int::times
"/" -> Int::div
else -> error("invalid operator")
}
fun evalRPN(tokens: Array<String>): Int =
tokens.fold(mutableListOf<Int>()) { stack, token ->
when (token) {
"+", "-", "*", "/" -> {
check(stack.size >= 2)
val r = stack.removeLast()
val l = stack.removeLast()
stack.add(getFunction(token)(l, r))
}
else -> {
stack.add(token.toInt())
}
}
stack
}.last()
}