알고리즘 풀이

[JAVASCRIPT] 백준 10798번 문제 풀이

Lv1_junior_dev 2023. 4. 7. 19:29

❗ 풀이

let input = require('fs').readFileSync('dev/stdin')
                         .toString()
                         .trim()
                         .split('\n').map(str => str.replace(/\r/g, ''));

let maxLength = Math.max(...input.map(i => i.length));

let result = [];

for (i = 0; i < maxLength; i++) {
    for (j = 0; j < input.length; j++) {
        input[j][i] === undefined ? null : result.push(input[j][i]);
    }
}

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

1. Math.max()와 map을 통해 배열 내 문자열 중 가장 긴 값을 maxLength로 정의

2. 결과 출력을 위한 빈배열 정의

3. 이중 for문으로 세로 읽기 / 길이가 다른 배열이 있으므로 배열이 존재할 때만 결과값을 result 배열에 push

4. 배열 내 문자열을 join()을 통해 합하여 출력