알고리즘

프로그래머스 - 대충 만든 자판

최데브 2024. 8. 11. 18:50

여러번을 눌러도 결국 필요한건 가장 적게 누르고 어떤 문자를 만들 수 있다는 정보가 가장 중요하다.

그래서 map 에다가 이미 저장된 key가 있다면 어떤게 더 적게 만들 수 있는 상황인지 체크해서 다시 저장해준다.

 

그리고 뒤에 헷갈렸던 부분은 여러문자열중 하나만이라도 만들 수 없다면 기존의 count 는 다 무시되고 -1 로 만들어줘야한다. 이 부분을 빠뜨려서 헤맸다.

import java.util.*
class Solution {
    fun solution(keymap: Array<String>, targets: Array<String>): IntArray {
        var answer = mutableListOf<Int>()
        var map = mutableListOf<MutableList<Char>>()
        var count = mutableMapOf<Char,Int>()
    
        for(i in 0 .. keymap.size-1){
            for(j in 0 .. keymap[i].length-1){
                if(count.containsKey(keymap[i][j])){
                    var temp = count.get(keymap[i][j])!!
                    count.put(keymap[i][j] ,minOf(temp , j+1))
                }else{
                    count.put(keymap[i][j] , j+1)
                }
            }
        }
        
        for(i in 0 .. targets.size-1){
            var tempCount = 0
            var check = 0
            var completeCount = targets[i].length
            for(j in 0 .. targets[i].length-1){
                if(count.containsKey(targets[i][j])){
                    tempCount += count.get(targets[i][j])!!
                    check++
                }
            }
            if(tempCount == 0 || check != completeCount){
                tempCount = -1
            }
            
            answer.add(tempCount)
        }
        
        return answer.toIntArray()
    }
}
반응형