반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

학급 회장(해쉬, Map) 본문

코딩테스트 with JS/자바스크립트 알고리즘 문제풀이(인프런)

학급 회장(해쉬, Map)

5_hyun 2022. 8. 26. 17:07

해결법

처음에 나는 이 문제를 객체를 이용해서 풀었다. 하지만 이 문제는 Map이란 자료구조를 사용하면 쉽게 풀 수 있다. 

let hash = new Map();

이렇게 생성할 수 있다.

 

hash.has(x): x가 포함되어 있는지 알 수 있다.

hash.set(x, 1): x라는 문자를 1로 초기화해준다.

hash.get(x): x의 key 값을 가져와 준다.

 

코드

<html>
  <head>
    <meta charset="UTF-8" />
    <title>출력결과</title>
  </head>
  <body>
    <script>
      function solution(s) {
        let answer;

        let hash = new Map();

        for (let x of s) {
          if (hash.has(x)) hash.set(x, hash.get(x) + 1);
          else hash.set(x, 1);
        }

        let max = Number.MIN_SAFE_INTEGER;

        for (let [key, value] of hash) {
          if (max < value) {
            max = value;
            answer = key;
          }
        }

        return answer;
      }

      let str = "BACBACCACCBDEDE";
      console.log(solution(str));
    </script>
  </body>
</html>
728x90
반응형
Comments