백준

[실버] 단어 정렬 (1181번)

chsua 2022. 11. 25. 11:32

문제

알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.

  1. 길이가 짧은 것부터
  2. 길이가 같으면 사전 순으로

 

입력

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

 

출력

조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.

 

내 답안:
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\\n");
input.shift() ;
let trans = new Set(input) ;
trans = [...trans] ;

let arr = [] ;
trans.forEach(x => arr.push([x, x.length])) ;
arr.sort() ;
arr.sort((a,b) => a[1] - b[1]) ;
for (i=0; i < arr.length ; i ++ ){
    if (arr[i] != arr[i-1] ) console.log(arr[i][0])
}

>> 시간 너무 오래걸림. trans 한번 반복, arr 세번 반복해서 그런가봄
수정된 내 답안:
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\\n");
input.shift() ;

let trans = [...new Set(input)] ;

trans.sort((a,b) => {
    if (a.length == b.length ){
        if (a < b)  return -1 
    }
    return a.length - b.length
}) ;
console.log(trans.join("\\n")) ;

// 속도 훨씬 줄어들음, 1회 반복으로 완성할 수 있음
// 소문자보다 대문자가 작음
// 동일한 알파벳이면 길이가 긴 것
// sort > 음수면 a가 먼저, b가 뒤

'백준' 카테고리의 다른 글

[실버] 카드2 (2164번)_JS  (0) 2022.11.28
[실버] 수찾기 (1920번)_JS  (0) 2022.11.28
[실버] 체스판 다시 칠하기 (1018번)  (0) 2022.11.25
[실버] 로프 (2217번)  (0) 2022.11.25
[실버] 베스트셀러 (1302번)  (0) 2022.11.25