728x90

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

Code

https://github.com/DasolPark/Algorithm_JavaScript/commit/32a64dbe8893d8f448507bb4900a155eb54a5764

😢 C언어로 자주 알파벳 가지고 놀았었는데, 기억이 잘 나지 않아서 검색을 좀 했다.
JavaScript로 ASCII Code 다루는 방법을 익혀서 새로웠지만 재밌었다.

😊 Solution 1)
단순하게 한 번 풀어보고자, 모든 알파벳을 배열에 담고 비교해보았다. for ... of를 이용해서 알파벳을 하나씩 반복해주고,
if else를 이용해서 해당 알파벳이 있다면 index를, 없다면 -1를 배열로 저장하였다. 출력은 join(' ')으로 형식을 맞춰주면 된다.


Solution 2)
먼저, 결과값을 담아줄 result array를 선언하였다. 그리고
for loop의 범위로 a-z를 주었다. 'a'는 ASCII Code 97번이고, 'z'는 ASCII Code 122번이기 때문에 97-122까지 반복 실행된다.
입력된 문자열(input 변수)에 해당하는 알파벳이 있다면 그 값의 index를, 없다면 -1를 반환하여 result array에 저장한다.
마지막으로, join(' ')을 통해 출력 형식을 맞춰 주면 된다.

가장 중요한 것-1 또는 해당 index라는 키워드가 나왔을 때, indexOf를 떠올릴 수 있어야 한다.

✔ String.prototype.charCodeAt()

각 알파벳의 ASCII Code를 알아내기 위해 사용하였다.
JavaScript-helper method에서 예제를 다뤄 보겠다.

✔ String.fromCharCode()

해당 ASCII Code에 해당하는 문자를 반환한다.
indexOf안에 찾고자하는 character를 넣기 위해 사용했다.(a-z의 ASCII Code가 순서대로 들어간다)
JavaScript-helper method에서 예제를 다뤄 보겠다.

✔ String.prototype.indexOf()

입력받은 값중에 해당 알파벳이 있는지, 있다면 그 위치(index)를 반환받고, 없다면 -1을 반환받기 위해 사용하였다.
JavaScript-helper method에서 예제를 다뤄 보겠다.

Full Code

// 2nd Solution
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString();
 
const input = 'baekjoon';
const result = [];
 
for (let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
result.push(input.indexOf(String.fromCharCode(i)));
}
 
console.log(result.join(' '));
 
// 1st Solution(not so good)
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
 
// const input = ['baekjoon'];
// const checker = [
// 'a',
// 'b',
// 'c',
// 'd',
// 'e',
// 'f',
// 'g',
// 'h',
// 'i',
// 'j',
// 'k',
// 'l',
// 'm',
// 'n',
// 'o',
// 'p',
// 'q',
// 'r',
// 's',
// 't',
// 'u',
// 'v',
// 'w',
// 'x',
// 'y',
// 'z'
// ];
 
// const result = [];
 
// for (let char of checker) {
// if (input[0].includes(char)) {
// result.push(input[0].indexOf(char));
// } else {
// result.push(-1);
// }
// }
 
// console.log(result.join(' '));

+ Recent posts