[백준] 1181 단어 정렬 Node.js

Janet·2023년 10월 7일
0

Algorithm

목록 보기
264/314

문제

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

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

단, 중복된 단어는 하나만 남기고 제거해야 한다.

입력

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

출력

조건에 따라 정렬하여 단어들을 출력한다.

예제 입력 1

13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours

예제 출력 1

i
im
it
no
but
more
wait
wont
yours
cannot
hesitate

문제풀이

✅ 풀이 #1

  • 중복 단어 제거를 위해 Set()을 사용한다.
  • 알파벳 순 정렬을 위해 sort()를 하고, 단어 길이별 정렬을 위해 아래와 같이 sort를 다시 사용.
  • 단어 길이가 짧은 것부터 정렬 하기위해 sort((a,b) => a.length - b.length);
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let [N, ...words] = require('fs').readFileSync(filePath).toString().trim().split('\n');
const unique = new Set(words); // 중복 제거를 위한 Set
const sorted = [...unique].sort().sort((a, b) => a.length - b.length);
console.log(sorted.join('\n'));

✅ 풀이 #2

  • 알파벳 순 정렬에는 내장 메서드 localeCompare()를 사용한 방법
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let [N, ...words] = require('fs').readFileSync(filePath).toString().trim().split('\n');
const unique = new Set(words); // 중복 제거를 위한 Set
const sorted = [...unique].sort((a, b) => {
  // 길이 같으면 알파벳 순으로 정렬
  if (a.length === b.length) {
    return a.localeCompare(b);
  }
  return a.length - b.length;
});

console.log(sorted.join('\n'));
profile
😸

0개의 댓글