알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
단, 중복된 단어는 하나만 남기고 제거해야 한다.
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
조건에 따라 정렬하여 단어들을 출력한다.
13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours
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'));