알고리즘/백준

[boj 10808] 알파벳 개수 -js

jinux127 2022. 3. 10. 13:10
// 알파벳 개수

const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
const input = require('fs').readFileSync(filePath).toString().trim().split(/\s/);

const S = input.shift();

const sol = (S) =>{
    const charCode_a = 'a'.charCodeAt();
    const charCode_z = 'z'.charCodeAt();
    const count_alphabet = new Array(charCode_z-charCode_a+1).fill(0);

    for (let i = 0; i < S.length; i++) {
        count_alphabet[S[i].charCodeAt() - charCode_a]++;
    }

    console.log(count_alphabet.join(' '));
}

sol(S);

a부터 z까지의 차이를 사이만큼 배열을 만들어 해당 인덱스의 개수를 증가 시켜줬다..

 

다른 방법도 찾아봤는데 

const s = require("fs").readFileSync("/dev/stdin").toString().split("");

const alphabet = "abcdefghijklmnopqrstuvwxyz";
const counts = new Array(26).fill(0);

s.forEach(i => counts[alphabet.indexOf(i)]++);

console.log(counts.join(" "));

알파벳을 직접 입력해 그 문자열의 인덱스를 조회하는 방법도 있었다.