Skip to content

Improved Node and task 150 #635

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions src/main/kotlin/com_github_leetcode/Node.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package com_github_leetcode

import java.util.StringJoiner
import kotlin.collections.ArrayList

class Node {
var `val`: Int
var neighbors: List<Node>
Expand All @@ -23,18 +20,14 @@ class Node {
}

override fun toString(): String {
val result = StringJoiner(",", "[", "]")
for (node in neighbors) {
return neighbors.joinToString(separator = ",", prefix = "[", postfix = "]") { node ->
if (node.neighbors.isEmpty()) {
result.add(node.`val`.toString())
node.`val`.toString()
} else {
val result2 = StringJoiner(",", "[", "]")
for (nodeItem in node.neighbors) {
result2.add(nodeItem.`val`.toString())
node.neighbors.joinToString(separator = ",", prefix = "[", postfix = "]") { nodeItem ->
nodeItem.`val`.toString()
}
result.add(result2.toString())
}
}
return result.toString()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@ package g0101_0200.s0150_evaluate_reverse_polish_notation
// #Medium #Top_Interview_Questions #Array #Math #Stack #Programming_Skills_II_Day_3
// #2022_10_09_Time_233_ms_(88.82%)_Space_36.7_MB_(91.45%)

import java.util.function.BiFunction

class Solution {
val op = mapOf<String, BiFunction<Int, Int, Int>>(
"/" to BiFunction { a, b -> a / b },
"*" to BiFunction { a, b -> a * b },
"+" to BiFunction { a, b -> a + b },
"-" to BiFunction { a, b -> a - b }
val op = mapOf<String, (Int, Int) -> Int>(
"/" to { a, b -> a / b },
"*" to { a, b -> a * b },
"+" to { a, b -> a + b },
"-" to { a, b -> a - b }
)
fun evalRPN(tokens: Array<String>): Int {
val stack = ArrayDeque<String>()
for (t in tokens) {
if (op.contains(t)) {
val b = stack.removeFirst().toInt()
val a = stack.removeFirst().toInt()
val c = op.getValue(t).apply(a, b)
val c = op.getValue(t).invoke(a, b)
stack.addFirst(c.toString())
} else {
stack.addFirst(t)
Expand Down
Loading