-
프로그래머스 / 대충 만든 자판코딩 테스트/Level 1 2023. 2. 25. 14:15반응형
https://school.programmers.co.kr/learn/courses/30/lessons/160586
딕셔너리, 맵을 이용 하자.
키를 누름 횟수가 작은 것을 기준으로 딕셔너리에 저장한 뒤...
코틀린
class Solution { fun solution(keymap: Array<String>, targets: Array<String>): IntArray { val answer = mutableListOf<Int>() val counter = mutableMapOf<Char, Int>() for (each in keymap) for ((index, key) in each.withIndex()) if ((counter[key] ?: index) >= index) counter[key] = index for (target in targets) { var touch = 0 for (key in target) { val temp = counter[key] if (temp == null) { touch = -1 break } else touch += temp + 1 } answer.add(touch) } return answer.toIntArray() } }
class Solution { fun solution(keymap: Array<String>, targets: Array<String>): IntArray { val counter = keymap .map { it.withIndex() } .flatten() .groupBy { it.value } .map { it.key to it.value.minOf { each -> each.index + 1 } } .toMap() return targets.map { it.sumOf { key -> counter[key] ?: let { return@map -1 } } }.toIntArray() } }
파이썬
def solution(keymap, targets): answer = [] key_dict = {} for each in keymap: for index, key in enumerate(each): key_dict.setdefault(key, index) if key_dict[key] > index: key_dict[key] = index for target in targets: temp = 0 for key in target: if key in key_dict: temp += key_dict[key] + 1 else: temp = -1 break answer.append(temp) return answer
golang
func solution(keymaps []string, targets []string) (result []int) { counter := map[rune]int{} for _, keymap := range keymaps { for index, key := range keymap { value, exists := counter[key] if index += 1; !exists { counter[key] = index } else { if value > index { counter[key] = index } } } } for _, row := range targets { sum := 0 for _, each := range row { temp, exists := counter[each] if !exists { sum = -1 break } sum += temp } result = append(result, sum) } return }
반응형