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:
parent
d7e8cc6f46
commit
589ae3bcea
1 changed files with 29 additions and 0 deletions
29
kt/evaluate-reverse-polish-notation.kt
Normal file
29
kt/evaluate-reverse-polish-notation.kt
Normal 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()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue