From 5d96b81e93f0234c5ea1dc926b37f1a9481a1f72 Mon Sep 17 00:00:00 2001 From: isaiahliu Date: Tue, 17 Dec 2024 00:59:42 +0800 Subject: [PATCH] 1 --- src/main/kotlin/p32xx/Problem3291.kt | 52 ++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/kotlin/p32xx/Problem3291.kt diff --git a/src/main/kotlin/p32xx/Problem3291.kt b/src/main/kotlin/p32xx/Problem3291.kt new file mode 100644 index 00000000..2d62a4d0 --- /dev/null +++ b/src/main/kotlin/p32xx/Problem3291.kt @@ -0,0 +1,52 @@ +package p32xx + +import util.expect + +fun main() { + class Solution { + fun minValidStrings(words: Array, target: String): Int { + class Trie(val depth: Int) { + val children = arrayOfNulls(26) + } + + val root = Trie(0) + words.forEach { + var current = root + it.forEach { ch -> + current = current.children[ch - 'a'] ?: Trie(current.depth + 1).also { + current.children[ch - 'a'] = it + } + } + } + + var dp = hashMapOf(root to 1) + + target.forEach { ch -> + val newDp = hashMapOf() + var min = Int.MAX_VALUE + dp.forEach { (node, count) -> + node.children[ch - 'a']?.also { + newDp[it] = count + min = minOf(min, count) + } + } + + if (min < Int.MAX_VALUE) { + newDp[root] = min + 1 + } + + dp = newDp + } + + return dp.values.minOrNull() ?: -1 + } + } + + expect { + Solution().minValidStrings( + arrayOf( + "abc", "aaaaa", "bcdef" + ), "aabcdabc" + ) + } +}