[프로그래머스] 대충 만든 자판 자바 코드

mango·2023년 3월 1일
0
post-thumbnail

* 알고리즘:

  1. keymap을 모두 읽으면서 hash map에 keymap에 존재하는 알파벳별 최소 입력 횟수를 put
  2. targets를 모두 읽으면서 hash map에서 최소 입력횟수를 조회 및 sum
  3. sum값을 answer에 할당

* Things I learnt

  1. hashmap 과 사용 함수들
  2. string의 문자 하나씩 읽는 방법 : str.charAt(index)
  3. 없는 알파벳일 때: hashmap에 null값이 조회될때 예외처리

* 코드

import java.util.*;

class Solution {
    public int[] solution(String[] keymap, String[] targets) {
        int[] answer = new int[targets.length];
        HashMap <Character, Integer> hm = new HashMap <Character, Integer>();
        
        for(int i = 0; i < keymap.length; i++){
            for(int j = 0; j < keymap[i].length(); j++){
                if(hm.get(keymap[i].charAt(j)) == null || hm.get(keymap[i].charAt(j)) > j+1)
                    hm.put(keymap[i].charAt(j),   j+1);
            }
        }
        //System.out.println(hm.size());
        
        for(int i = 0; i < targets.length; i++){
            
            int sum = 0;
            for(int j = 0; j < targets[i].length(); j++){
                if(hm.get(targets[i].charAt(j)) != null)
                    sum += hm.get(targets[i].charAt(j));
                else {
                    sum = -1;
                    break;
                }
            }
            answer[i] = sum;
        }
        
        return answer;
    }
}


거의 한번만에 통과! yay 신난다

profile
앎의 즐거움을 아는 나는 mango ♪

0개의 댓글