From 66888a41091cb053cf772c9d70d66b3e47aa149e Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 13 Aug 2022 22:50:35 +0200 Subject: [PATCH] =?UTF-8?q?problems:=20add=20=E2=80=9E30.=20Substring=20wi?= =?UTF-8?q?th=20Concatenation=20of=20All=20Words=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...bstring-with-concatenation-of-all-words.kt | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 problems/substring-with-concatenation-of-all-words.kt diff --git a/problems/substring-with-concatenation-of-all-words.kt b/problems/substring-with-concatenation-of-all-words.kt new file mode 100644 index 0000000..640e1f0 --- /dev/null +++ b/problems/substring-with-concatenation-of-all-words.kt @@ -0,0 +1,29 @@ +class Solution { + private fun buildTable(words: Sequence): Map { + val table = mutableMapOf() + + words.forEach { + table.put(it, 1 + table.getOrElse(it) { 0 }) + } + + return table + } + private fun buildTable(s: String, length: Int): Map = + buildTable(s.chunked(length).asSequence()) + + fun findSubstring(s: String, words: Array): List { + val expectedFrequencies = buildTable(words.asSequence()) + val wordLen = words.first().length + val windowSize = wordLen * words.size + + return s + .windowed(windowSize) + .zip(s.indices) + .filter { (window, _) -> + val frequencies = buildTable(window, wordLen) + frequencies == expectedFrequencies + } + .map { (_, idx) -> idx } + .toList() + } +}