호지

[프로그래머스] 대충 만든 자판 JS 본문

알고리즘/프로그래머스

[프로그래머스] 대충 만든 자판 JS

_hoji

keymap을 탐색해서, map에 정의된 key의 최솟값을 먼저 찾으면 쉽게 해결할 수 있는 문제이다.

map에 정의된 key값의 최솟값을 찾기 위해 이중 for문을 돌려서,

처음 본 key값이거나, 이전 key값보다 작을때 count를 업데이트한다.

이후 targets를 탐색하여 합을 구하는데,

key값이 map에 정의된적이 없을 때, 즉 undefined일 때는 -1이 되도록 했다

function solution(keymap, targets) {
  let count = {};
  let answer = [];
  for(let i=0; i<keymap.length; i++){
      for(let j=0; j<keymap[i].length; j++){
          if(!count[keymap[i][j]] || count[keymap[i][j]] > j){
              count[keymap[i][j]] = j+1;  
          }
      }
  }
  for(let target of targets){
      let sum = 0;
      for(let i=0; i<target.length; i++){
          if(!count[target[i]]){
              sum = -1;
              break;
          }
          sum += parseInt(count[target[i]]);
      }
      answer.push(sum)
  }
  return answer;
}

https://school.programmers.co.kr/learn/courses/30/lessons/160586

Comments