KotlinAlgorithm#18 (POG 대충 만든 자판)

박채빈·2023년 7월 19일
0

KotlinAlgorithm

목록 보기
18/28
post-thumbnail

POG 대충 만든 자판

링크

코드

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()

이부분 간단하게 수정도 가능할 듯

profile
안드로이드 개발자

0개의 댓글