class Solution {
fun solution(keymap: Array<String>, targets: Array<String>): IntArray {
var answer = ArrayList<Int>()
var keys = ""
keymap.forEach { keys += it }
val keySet = keys.toSet()
val keyCountMap: MutableMap<Char, Int> = keySet.associateWith { 0 }.toMap().toMutableMap()
keyCountMap.keys.forEach keys@ { key ->
var index = 101
keymap.forEach inner@ { command ->
val tmp = command.indexOf(key).coerceAtMost(index).takeIf { it >= 0 } ?: return@inner
index = tmp.coerceAtMost(index)
}
keyCountMap[key] = index + 1
}
targets.forEach out@ { target ->
var result = 0
target.forEach { key -> if(!keyCountMap.containsKey(key)) {
answer.add(-1)
return@out
} }
target.forEach { key -> result += keyCountMap[key] ?: Int.MIN_VALUE }
answer.add(result.takeIf { it > 0 } ?: -1)
}
return answer.toIntArray()
}
}
var keys = "" keymap.forEach { keys += it } val keySet = keys.toSet()
이부분 간단하게 수정도 가능할 듯