- 난이도: Lv1
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/160586
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/1/160586. 대충 만든 자판
풀이 시간 : 24분
import java.util.*;
class Solution {
public int[] solution(String[] keymap, String[] targets) {
int[] answer = new int[targets.length];
Map<Character, Integer> map = new HashMap<>();
//1. keymap
for(int i=0; i<keymap.length; i++){
String keys = keymap[i];
char key = keymap[i].charAt(i);
int value = map.getOrDefault(key, i+1);
map.put(key, Math.min(value, i+1));
}
//2. targets
for(int i=0; i<targets.length; i++){
for(int j=0; j<targets[i].length(); j++){
char key = targets[i].charAt(j);
if(map.containsKey(key)){
answer[i] += map.get(key);
}
}
}
return answer;
}
}
//before
//1. keymap
for(int i=0; i<keymap.length; i++){
String keys = keymap[i];
char key = keymap[i].charAt(i);
int value = map.getOrDefault(key, i+1);
map.put(key, Math.min(value, i+1));
}
//after
//1. keymap
for(int i=0; i<keymap.length; i++){
String keys = keymap[i];
for(int j=0; j<keymap[i].length(); j++){
char key = keymap[i].charAt(j);
int value = map.getOrDefault(key, j+1);
map.put(key, Math.min(value, j+1));
}
}
풀이 시간 : 29분(첫 풀이 시간 포함)
import java.util.*;
class Solution {
public int[] solution(String[] keymap, String[] targets) {
int[] answer = new int[targets.length];
Map<Character, Integer> map = new HashMap<>();
//1. keymap
for(int i=0; i<keymap.length; i++){
String keys = keymap[i];
for(int j=0; j<keymap[i].length(); j++){
char key = keymap[i].charAt(j);
int value = map.getOrDefault(key, j+1);
map.put(key, Math.min(value, j+1));
}
}
//2. targets
for(int i=0; i<targets.length; i++){
for(int j=0; j<targets[i].length(); j++){
char key = targets[i].charAt(j);
if(map.containsKey(key)){
answer[i] += map.get(key);
}
else {
answer[i] = -1;
break;
}
}
}
return answer;
}
}