mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems: add „30. Substring with Concatenation of All Words“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
9fa6578ce7
commit
66888a4109
1 changed files with 29 additions and 0 deletions
29
problems/substring-with-concatenation-of-all-words.kt
Normal file
29
problems/substring-with-concatenation-of-all-words.kt
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
class Solution {
|
||||||
|
private fun buildTable(words: Sequence<String>): Map<String, Int> {
|
||||||
|
val table = mutableMapOf<String, Int>()
|
||||||
|
|
||||||
|
words.forEach {
|
||||||
|
table.put(it, 1 + table.getOrElse(it) { 0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
return table
|
||||||
|
}
|
||||||
|
private fun buildTable(s: String, length: Int): Map<String, Int> =
|
||||||
|
buildTable(s.chunked(length).asSequence())
|
||||||
|
|
||||||
|
fun findSubstring(s: String, words: Array<String>): List<Int> {
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue