[JS] BOJ 1157번 단어공부

yeopto·2022년 1월 21일
0

Algorithm

목록 보기
9/11
post-thumbnail

출처

BOJ

https://www.acmicpc.net/problem/1157

문제

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

나의 풀이

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().toLowerCase();

const result = new Array(26).fill(0);

solution();

function solution() {
    "use strict";
    for (let i = 0; i < input.length; i++) {
        result[input.charCodeAt(i) - 97]++;
    }

    const max = Math.max(...result);
    const index = result.indexOf(max);

    let isSame = false;

    for (let j = 0; j < 26; j++) {
        if (result[j] === max && index != j) {
            isSame = true;
            break;
        }
    }
    console.log(isSame ? "?" : String.fromCharCode(index + 65));

대문자 소문자 가리지 않고 카운트하기 때문에 input을 소문자로 다 바꿔준다 → 26개의 result 배열(a~z)을 만든 후 값을 모두 0으로 초기화 → input길이만큼 반복하면서 input 요소의 알파벳의 아스키 숫자를 구한뒤 ‘a’는 97이기에 97을 빼주면 result의 인덱스가 알파벳 순서와 같게 됨 → 찾으면 result[]의 값을 1씩 카운트 → result에서 제일 큰 값을 찾아주고 → 큰 값의 인덱스가 무엇인지 체크 → “?” 출력을 위해 isSame이라는 변수를 false로 → result를 0부터 25까지 즉 ‘a’ 부터 ‘z’ 까지 확인 하며 max값이 같은게 있는지 확인 → 있으면 isSame 값 true → 삼항연산자로 true면 “?” 출력 false면 대문자로 바꿔서 출력(’A’는 65)

profile
https://yeopto.github.io로 이동했습니다.

0개의 댓글