whatisthis?

[백준] 10809번 - 알파벳 찾기 (node.js) 본문

ALGORITHM/BOJ (Node.js)

[백준] 10809번 - 알파벳 찾기 (node.js)

thisisyjin 2022. 7. 7. 15:08

JavaScript

문제

알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.

출력

각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다.
만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출력한다. 단어의 첫 번째 글자는 0번째 위치이고, 두 번째 글자는 1번째 위치이다.

예제

입력

baekjoon

출력

1 0 -1 -1 2 -1 -1 -1 -1 4 3 -1 -1 7 5 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

내 코드

const input = require('fs').readFileSync('/dev/stdin').toString();
let answer = [];

for(i=97; i<= 122; i++) {
    answer.push(input.indexOf(String.fromCharCode(i));
}

console.log(answer.join(' '));

'a'의 아스키코드는 97이고, 'z'의 아스키코드는 122이므로,
for문을 실행하여 각 알파벳이 존재하면 첫 인덱스를 반환하고, 없으면 -1을 반환하는 메서드인 indexOf()를 이용하여
answer 배열에 push 한 후, for loop 종료되고 난 후 join(' ') 으로 문자열로 합쳐 반환한다.

실행 결과

140ms / 9340KB


다른 코드

let input = require('fs').readFileSync('/dev/stdin').toString();
let answer = [];

answer.push(input.indexOf('a'));
answer.push(input.indexOf('b'));
answer.push(input.indexOf('c'));
answer.push(input.indexOf('d'));
answer.push(input.indexOf('e'));
answer.push(input.indexOf('f'));
answer.push(input.indexOf('g'));
answer.push(input.indexOf('h'));
answer.push(input.indexOf('i'));
answer.push(input.indexOf('j'));
answer.push(input.indexOf('k'));
answer.push(input.indexOf('l'));
answer.push(input.indexOf('m'));
answer.push(input.indexOf('n'));
answer.push(input.indexOf('o'));
answer.push(input.indexOf('p'));
answer.push(input.indexOf('q'));
answer.push(input.indexOf('r'));
answer.push(input.indexOf('s'));
answer.push(input.indexOf('t'));
answer.push(input.indexOf('u'));
answer.push(input.indexOf('v'));
answer.push(input.indexOf('w'));
answer.push(input.indexOf('x'));
answer.push(input.indexOf('y'));
answer.push(input.indexOf('z'));

console.log(answer.join(' '));

String.fromCharCode를 생략할 수 있지만, for loop를 풀어서 써서
가독성이 좋지 않고 코드 길이가 매우 길어졌다.
단, 성능은 똑같다!