From 8157017f38f92154f084456255075e132511b817 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 26 May 2024 00:41:14 +0200 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB140.=20Word=20Break=20II?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- kt/word-break-ii.kt | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 kt/word-break-ii.kt diff --git a/kt/word-break-ii.kt b/kt/word-break-ii.kt new file mode 100644 index 0000000..7310633 --- /dev/null +++ b/kt/word-break-ii.kt @@ -0,0 +1,59 @@ +class Solution { + private fun precomputeFrom( + words: List, + s: String, + dp: Map>, + start: Int, + ): List { + val valid = mutableListOf() + + (start.. end to s.substring(start..end) } + .filter { (_, word) -> words.contains(word) } + .forEach { (end, word) -> + when { + end == s.length - 1 -> valid.add(word) + else -> { + dp[end + 1]?.forEach { suffix -> + valid.add("$word $suffix") + } + } + } + } + + return valid + } + + fun wordBreak( + s: String, + wordDict: List, + ): List { + val dp = mutableMapOf>() + + s.indices.reversed().forEach { start -> + dp[start] = precomputeFrom(wordDict, s, dp, start) + } + + return dp.getOrDefault(0, emptyList()) + } +} + +fun main() { + val s = Solution() + + check( + s.wordBreak("catsanddog", listOf("cat", "cats", "and", "sand", "dog")).sorted() == + listOf( + "cats and dog", "cat sand dog", + ).sorted(), + ) + check( + s.wordBreak("pineapplepenapple", listOf("apple", "pen", "applepen", "pine", "pineapple")).sorted() == + listOf( + "pine apple pen apple", "pineapple pen apple", "pine applepen apple", + ).sorted(), + ) + check( + s.wordBreak("catsandog", listOf("cats", "dog", "sand", "and", "cat")) == emptyList(), + ) +}