Copy class Solution {
fun findSubstring (s: String , words: Array < String >): List < Int > {
val result = arrayListOf < Int >()
val total = java.util. LinkedList < String >()
val len = words[ 0 ].length
var word: String
var temp: Boolean
for (i in 0 .. s.length - len) {
if (i + len * words.size > s.length) break
total += words
for (j in 0 until words.size) {
word = s. substring (i + len * j, i + len * (j + 1 ))
temp = words.indices
. firstOrNull { word == words[it] }
?. let { true }
?: false
if (temp) total. remove (word) else break
}
if (total. isEmpty ()) result. add (i) else total. clear ()
}
return result
}
}
Copy class Solution {
fun findSubstring (s: String , words: Array < String >): List < Int > {
val result = arrayListOf < Int >()
val wordMap = hashMapOf < String , Int >()
val tempMap = hashMapOf < String , Int >()
val wordLen = words[ 0 ].length
val wordsLen = wordLen * words.size
val limit = s.length - wordLen
var tempWordRight: String
var tempWordLeft: String
var count: Int
var left: Int
var right: Int
for (w in words) {
wordMap[w] = (wordMap[w] ?: 0 ) + 1
}
for (i in 0 until wordLen) {
if (i + wordsLen > s.length) break
left = i
right = left
count = 0
tempMap. clear ()
while (right <= limit) {
tempWordRight = s. substring (right, right + wordLen)
if (wordMap[tempWordRight] == null ) {
left = right + wordLen
right = left
count = 0
tempMap. clear ()
} else {
tempMap[tempWordRight] = (tempMap[tempWordRight] ?: 0 ) + 1
right += wordLen
count ++
if (wordMap[tempWordRight] !! < tempMap[tempWordRight] !! ) {
while ( true ) {
tempWordLeft = s. substring (left, left + wordLen)
tempMap[tempWordLeft] = tempMap[tempWordLeft] !! - 1
count --
left += wordLen
if (tempWordLeft == tempWordRight) break
}
}
}
if (count == words.size) {
result. add (left)
}
}
}
return result
}
}