프로그래머스 LEVEL 1(가장 가까운 글자)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2022-12-10

  • 해결 방법 :

    • map 자료구조를 통해 문제 해결
    • 입력 받은 문자열 s를 돌며, map에 key값으로 c를 가지고 있지 않다면
      • answer에 -1 push()
      • 현재 c의 위치 map에 저장
    • map에 key값으로 c를 가지고 있다면
      • 현재 c의 위치와 map에 저장된 가장 가장 가까운 c의 위치의 차이를 answer에 push()
      • 현재 c의 위치 map에 저장
  • 회고 :

    • x
  • 코드

    function solution(s) {
      const answer = [];
      const map = new Map();
    
      for (let i = 0; i < s.length; i++) {
        const c = s[i];
    
        if (map.has(c)) {
          const diff = i - map.get(c);
          answer.push(diff);
        } else answer.push(-1);
    
        map.set(c, i);
      }
    
      return answer;
    }
    
  • 출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges